Coding Basics (JavaScript)
To learn some the basic programming concepts, we’ll use the online code editor, runjs.app. This will save us from having to download and install a real code editor like Visual Studio Code. There are many online code editors but this one is focused on JavaScript.
In this code editor, the left side is where we will write code. The right side is where we will output results. The right side mimics a browser’s console. A console is an output window that all browsers have. In chrome for example, you can show the console by right clicking anywhere in a page and selecting inspect. The console window is the second tab, next to elements. The elements tab shows she source code of the page which is also useful.
The online code editor in runjs will automatically run your code after you are done typing, but you can manually trigger the run action by clicking the play button in the top left.

One thing we can do in JavaScript is use console.log() to see what is happening in our code. If we pass a variable into the parenthesis, its value will be written to the console as output. Console.log() is one of several built-in JavaScript objects with methods, and we will learn more about those later. But for now let’s start with understanding something more fundamental, like variables.
You may just be getting started with learning about programming, but in short time you’ll be awesome at it. When you start building real projects, check out the Nano ASP.NET Boilerplate to learn advanced patterns and practices.
Variables
Variables are used to store data in memory. In JavaScript (JS) we can define a new variable by typing var and then some name. As with many languages, in JavaScript you should add a semicolon to end each line of code.
Variables without a value assigned from the start will be set to undefined. You can assign a value by writing an equals sign and then a value.
So let’s create a variable called myVariable and output it to the console window. You can add comments in your code with double forward slashes
var myVariable;
console.log(myVariable); // output is undefined
We can see in the console the value undefined being output. How interesting! Ok, now let’s assign it a value like 10. Incredible, the number 10 is output to the console.
Depending on the value given to a variable, JS will determine its type. There are several types that exist. Two of the most important ones are numbers and strings.
Whenever we assign a numeric value, JS will interpret the variable type to be number. Numbers are special because we can perform mathematical operations on them.
Create a new variable called result and assign it the value of myVariable plus 5. Replace the output of console.log() with result and we’ll see 15 written to the console.
var myVariable = 10;
var result = myVariable + 5;
console.log(result); // outputs 15
We can perform all kinds of mathematical operations on number types like addition (+), subtraction (-), multiplication (*), and division (/).
A string is another variable type. Strings are any series of characters, like text. When assigning strings to variables, the value must be encased in single or double quotation marks.
Changing the value of myVariable to “hello world” will cause JS to interpret this as a string type.
var myVariable = "hello world";
var result = myVariable + 5;
console.log(result); // outputs 'helloworld5'
The result will be ‘hello world5’ because anything added to strings will just be appended to the end. Also notice that the output of a string value will be shown in the console window surrounded by quotes, whereas numeric values will not.
It’s important to be aware of the distinction between numbers and strings because it can often be the source of errors in your code. Change the value of myVariable to “10” with quotation marks and the output of the result will be ‘105’.
var myVariable = "10";
var result = myVariable + 5;
console.log(result); // outputs '105'
The reason is that JS will treat myVariable as a string type due to the quotes. If we changed the addition operation to subtraction, we will see NaN output to the console, which stands for Not a Number. The plus operator works on strings to append values but none of the other mathematical operators do anything.
var myVariable = "hello world";
var result = myVariable - 5;
console.log(result); // outputs 'NaN'
In the world of programming languages, there are two types: strongly-typed (compiled) and loosly-typed (interpreted). JavaScript is a loosely-typed language, meaning that variable types will be determined on the fly based on inference. Strongly typed languages allow you to specify the type of variable when you create it. In a back-end language like C# for example, instead of typing var, we can instead type string and only string values will be permitted for that variable. While that might sound cumbersome, it’s actually better because it allows you to catch errors sooner than later.
Next we’ll learn about functions. We’ll learn more about variables in JavaScript as we go on. Strings and numbers are the two most common variable types. Other types are Booleans, objects, arrays, dates and functions.
Functions
Functions are another fundamental concept in almost all programming languages. Functions are blocks of code that we can run whenever we want. You can think of a function like a machine: we give it some input, it does something, and then gives us an output (or just does something useful behind the scenes).
To create a function, we use the function keyword, followed by a name, parentheses, and then curly braces for the code that runs when the function is called.
Let’s try creating our first function:
function doSomething () {
console.log("hello");
};
In this example, we’ve created a function called doSomething. Inside the curly braces, we have one line of code: a console.log() statement that should output “hello”.
But notice—nothing happens yet.
That’s because defining a function is just like writing instructions. If we want to run the instructions, we need to call the function by typing its name with parentheses at the end:
doSomething();
function doSomething () {
console.log("hello");
};
Now the console will output “hello”. That’s how we run (or “invoke”) the function.
Functions get more interesting when we allow them to accept input. We can pass parameters into the function—these are like variables that exist only inside the function.
var myVariable = 10;
doSomething(8);
function doSomething (multiplier) {
var result = myVariable * multiplier;
console.log("The result is: " + result);
}; // outputs 'the result is: 80'
Here, multiplier is the parameter. We’re taking myVariable from before, and performing some multiplication on it. The new value is stored in a local variable called result.
We can reuse this function with any multiplier value we want. When we call doSomething(8), the console shows “the result is: 80”.
As with parameters, any variables defined within a function will only exist there. If we try to reference the value of the result variable outside the function, an error will be thrown.
Sometimes, we want a function to give us something back. That’s where the return keyword comes in. It lets the function send a value back to wherever it was called.
var myVariable = 10;
console.log(doSomething(5)); // function returns a value
function doSomething (multiplier) {
var result = myVariable * multiplier;
return "The result is: " + result;
}; // outputs 'the result is: 50'
Conditional Logic
Conditional statements are blocks of code that run only if certain conditions are met. They start with the if keyword followed by the condition in parenthesis, and the code to be executed in brackets after that.
The condition is a test for true or false, usually using operators like equal to, less than, greater than, etc.
var amount = 150;
if (amount >= 100) {
console.log("You qualify for a discount!");
}
// output: 'You qualify for a discount!'
In this example, the code in brackets will only execute if the amount is greater than or equal to 100. If statements can be extended with else if, and else. Else if will check for another condition, and else is like a catch-all that will execute in the case that none of the others trigger.
var amount = 75;
if (amount >= 100) {
console.log("You qualify for a premium discount!");
} else if (amount >= 40 && amount < 100) {
console.log("You qualify for a basic discount!");
} else {
console.log("Sorry, no discount available.");
}
// output: 'You qualify for a basic discount!'
Now if the condition is between 40 and 99, the else if code will execute. If the condition is below 40, the else code will execute.
It’s important to note however that the condition tree execution will end whenever the first condition is met. So if the first condition is true, the second condition will not execute even if it is also true.
You can have as many else if branches as you want but there can only be one if and one else.
Another way to do conditional logic is by using a ternary operator. Since conditional logic is so common, this is a shorthand way to write it if there are only two possible outcomes.
let amount = 120;
let message = amount >= 100 ? "Discount applied!" : "No discount available";
console.log(message);
// output: 'Discount applied!'
The structure of a ternary operator is first is the condition, followed by a question mark, then the true output, a colon, and the false output. The output logic is limited to single-line code.
Objects & Methods
An object is a variable that contains one or more properties with their values, known as key-value pairs. It’s like a complex variable that is made up of more than just a single value. Usually objects represent some actual thing. For example a vehicle object might contain properties for manufacturer, type, year, model, and mileage.
var vehicle = {
manufacturer: "Toyota",
type: "sedan",
year: 2023,
model: "Camry",
mileage: 15000
};
// Accessing object properties
console.log(vehicle.manufacturer); // Toyota
console.log(vehicle["type"]); // sedan
An object is created like a variable with properties contained within braces. Values for the properties follow a colon and are comma separated.
You can define your own objects like we just did, but JavaScript has several special objects that are built in to the language. When we write console.log() we are actually using one of these built in objects, console, which has a method called log().
A method is like a function that belong to the object, and just like any other function, it is invoked with parenthesis and can sometimes take in parameters. Your own objects can contain methods too.
var car = {
make: "Honda",
model: "Civic",
year: 2022,
startEngine: function() {
return "Engine started!";
},
// Shorthand method syntax
stopEngine() {
return "Engine stopped!";
}
};
console.log(car.startEngine()); // output: 'Engine started!'
It’s common to work with objects in a list, known as an array. This is how data is returned by the back-end when retrieved from a database. The data is usually sent in JSON format, which stands for JavaScript Object Notation.
// JSON example - an array of objects
var vehicles = [
{
"manufacturer": "Toyota",
"type": "sedan",
"year": 2023,
"model": "Camry",
"mileage": 15000
},
{
"manufacturer": "Honda",
"type": "SUV",
"year": 2022,
"model": "CR-V",
"mileage": 12000
},
{
"manufacturer": "Ford",
"type": "truck",
"year": 2021,
"model": "F-150",
"mileage": 20000
}
];
// Accessing data in the JSON array
console.log(vehicles[1].manufacturer); // Honda
console.log(vehicles[2].model); // F-150
Arrays
Arrays are a type of variable that contains a collection of items. The items contained within an array can be of any type; most commonly strings, numbers, or objects. Arrays in JavaScript are ordered collections, meaning each item has a specific position.
To declare an empty array, create a variable followed by empty brackets.
var turtles = [];
You can also initialize an array with values:
var colors = ["red", "blue", "green"];
var numbers = [1, 2, 3, 4, 5];
var mixed = [42, "hello", true, { name: "John" }];
Arrays have built-in methods which we can use to manage the data stored within them. We can use the push method to add a new item to the end of an array. Let’s add some items to our turtles array, and then log it to the console.
turtles.push("Leonardo");
turtles.push("Raphael");
turtles.push("Donatello");
turtles.push("Michelangelo");
console.log(turtles); // ["Leonardo", "Raphael", "Donatello", "Michelangelo"]
Each item in the array is indexed with a number starting from zero. We can refer to any item using their index number.
console.log(turtles[0]); // "Leonardo"
console.log(turtles[2]); // "Donatello"
There are different methods for removing items from an array. The pop() method removes the last item in the array and returns it:
var removedTurtle = turtles.pop(); // Removes "Michelangelo"
console.log(removedTurtle); // "Michelangelo"
console.log(turtles); // ["Leonardo", "Raphael", "Donatello"]
To remove an item at a specific index, use the splice() method:
turtles.splice(1, 1); // Remove 1 item at index 1 (Raphael)
console.log(turtles); // ["Leonardo", "Donatello"]
The length property tells you how many items are in an array:
console.log(turtles.length); // 2
Arrays also have many other useful methods like forEach(), map(), filter(), and reduce() that let you process data in powerful ways.
Loops
Loops are blocks of code that iterate until a condition is met. They’re essential for processing data collections and performing repetitive tasks without duplicating code. There are several kinds of loops we can construct in JavaScript, each with its own use cases. Here are the two most useful:
While Loop
The while loop executes a block of code as long as a specified condition is true.
var number = 0;
var myArray = [];
while (number <= 60) {
myArray.push(number);
number += 15;
}
console.log(myArray); // [0, 15, 30, 45, 60]
The keyword while is followed by a condition within parentheses. The code in braces is then executed repeatedly until the condition is no longer true. In this example, we start with a number zero, add it to our myArray and we add 15 each iteration. This loop will stop running once the number value exceeds 60. When we log it to the console we can see the result with 5 items.
The plus equals (+=) is a shorthand way to increment by a value. Another useful shorthand incrementor is the plus plus (++) to increment by one. If we wrote number++ the value of myArray would contain every number from 0 to 60.
If we didn’t increment the number variable, the end condition would never be met. Whenever the end condition of a loop can’t be met, its called an infinite loop and will throw an error!
ForEach Loop (Method)
If you are working with arrays, the forEach method is quite useful. It executes a function for each element in an array.
var turtles = ["Leonardo", "Raphael", "Donatello", "Michelangelo"];
turtles.forEach((turtle, index) => {
console.log(`Turtle #${index + 1}: ${turtle}`);
});
// output:
// 'Turtle #1: Leonardo'
// 'Turtle #2: Raphael'
// 'Turtle #3: Donatello'
// 'Turtle #4: Michelangelo'
Here we output the name of each ninja turtle along with a number. We add + 1 to the index since indexes start at zero.
Loops are fundamental to programming as they allow us to process data efficiently and automate repetitive tasks. There are other kinds of loops but these two are the most useful.
Conclusion
There is of course so much more to learn but these concepts are the core of programming. Knowing these fundamentals are an important first step in anyone’s journey in learning how to code.
In the next module, we will apply these concepts as we build a web application front-end. We will set up a real development environment, learn about HTML and CSS, and more. In no time, you’ll be coding in your sleep and building the next big thing. When that time comes, don’t forget to check out the Nano ASP.NET Boilerplate.