Just like every other programming language, JavaScript has a number of fundamentals that add up to make it a powerful programming language.
In this article, I share bite-sized explanations of 12 JavaScript fundamentals. This article is put together with beginners in mind. The goal is to give you a hint of the basics in a compressed format.
By no means, is this a full guide, however, if you need a reference guide, this can serve. With no further ado, let's get started!
Contents
- Code structure
- Modern "use strict"
- Variables
- Data types
- Interaction: alert, prompt, confirm
- Type conversions
- Basic operators
- Comparison
- Conditionals
- Switch Statement
- Loops
- Functions
Code Structure
The pattern used to write code is what we refer to as the code structure. Every programming language has its unique code structure. In JavaScript, code (which consists of a series of instructions), is written as lines of statements with ending semicolons. A statement can be likened to a sentence in the English language.
Here is an example of a statement in JavaScript:
// A single JavaScript statement
alert("Hello there!");
The semicolon indicates the end of the statement, just like what a full stop does in a sentence.
When writing a JavaScript program, it is compulsory that you separate statements written next to each other using a semi-colon.
// Create a variable greeting and alert its value
const greeting = "Hello world"; alert(greeting);
When you have these statements on separate lines, the semicolon becomes optional. However, it is best practice to include a semicolon regardless of a new line. This reduces the probability of error.
Modern "use strict"
Before the introduction of ECMAScript5 in 2009, adding new features to JavaScript did not affect its old functionality. This means JavaScript was backward compatible at that time.
But right now, it's a different ball game with modern JavaScript (ES5 and beyond).
"use strict" compels the JavaScript code to be executed in "strict mode". The use of " use strict" helps you write a cleaner code by checkmating statements that could throw an error, e.g., an undeclared variable.
"use strict" is written at the top of your code.
However, a modern approach to writing code may be to group them into classes and modules. With this, you do not need to include "use strict" at the top because they are enabled automatically.
Variables
In simple terms, a variable is a memory container that stores a value. This value can be changed.
Think about your favorite football club, yeah? That's a variable that has a value, say, Manchester United.
In JavaScript, you declare a variable using var, let, or const.
A variable can hold any kind of data type - String, Number, Boolean, and so on. Variables are mutable (i.e. they can be changed) and can be reassigned values.
Here's an example using the previous analogy:
// declare a variable and assign a value to it
1. let footballClub = "Manchester United"; //variable assigned to a string value
2. footballClub = 1; //variable reassigned to number
3. footballClub = true; //variable reassigned to Boolean
When a variable is declared without assigning a value, its default value is undefined.
Data Types
Every value in JavaScript has a type. For example, a Boolean or Number. JavaScript data type is of two categories; primitives and objects.
A primitive data type is any value that is not an object and has no methods. Primitives are immutable (i.e., they cannot be changed). JavaScript has 7 primitive data types which include:
Numbers - Numbers can be integers or floating-point numbers. Unlike strings, they are written without quotes (" "). For example:
let num = 256.89
You can perform basic mathematical operations on numbers e.g addition, multiplication, subtraction, division, etc.
JavaScript has "special" numbers classified as Infinity, -Infinity, and NaN.
Infinity - According to MDN docs:
“Infinity is a property of the global object. In other words, it is a variable in global scope. The initial value of Infinity is Number.POSITIVE_INFINITY. The value Infinity (positive infinity) is greater than any other number.”
NaN - This stands for Not a Number. NaN is the result of an invalid operation.
BigInt - BigInt is used to represent integer values of arbitrary length. It is written by adding n to an integer literal.
let num = 1234567897654321n //This is a BigInt
Typical usage of BigInt is in cryptography.
String - In JavaScript, a string is a text surrounded by quotes. You can either use a single quote (' '), double quotes (" ") or backticks (``).
Single and double quotes are the same, however, backticks are used to embed variables using ${ }.
1. let name = "JavaScript";
2. alert(` I am learning ${name}`); // I am learning JavaScript
Boolean - A boolean is a data type that returns either true or false as its values. When a comparison is done, the result is usually a Boolean value.
1. let isLessThan = 3 < 1;
2. alert(isLessThan); //false
Null - Null means "nothing", "unknown value" or "empty". It can be assigned to a variable if you want the variable to be empty.
Undefined - When a variable is not assigned a value, its default value is undefined.
// declare an unassigned variable
1. let name;
2. alert(name); // undefined
Symbol - A symbol can be used as an object property.
Objects - An Object is a data type that can be used to represent a collection of data. Unlike primitives that can represent only one type, objects can store complex data entities.
Interactions
There are certain built-in functions in the browser that allows user interaction. They are:
alert: This is used to show a response or return an output message. The message pops up in a 'mini-window' on the screen of your computer.
alert("Greeting");
prompt: This is used to request input from a user. It takes in two arguments - input request text, default initial value(optional).
confirm: This pops up with a question and two buttons- Ok and Cancel. Clicking Ok returns true while cancel returns false.
Type Conversion
At some point, you may need to interchange types for any reason. This can be done by wrapping the expected value with the built-in type function you want to convert to.
Operators and functions will most times convert values inserted to the correct type.
For example, alert() will automatically convert its value type to a string.
Boolean will convert a value to either true or false.
1. let value = "123";
2. alert(typeof value); //string
// convert string to a Number type
3. let newValue = Number(value);
4. alert(typeof newValue); //string
typeof
is the operator used to check for value type.
A typical scenario that may need conversion is when you expect input as a number but the value is to be read from a string-based source.
Basic Operators
Like in school maths, JavaScript also supports basic arithmetic operations. A list of them are:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division(/)
- Modulus (%)
- Exponentiation (**)
While the first four works the same way in school maths, a few words on modulus and exponentiation.
Modulus (%): This symbol is in no way performing a percentage operation. Modulus returns the remainder integer of a division operation.
alert(10 % 3) // 1, a remainder of 10 divided by 3
Exponentiation: In school maths, we write b^d. In code, we write this as b**d.
alert(4**2) //4^2 =16
Some operators in JavaScript are not only used for arithmetic purposes.
For example, + operator is also used for string concatenation.
1. let hobby = "I love to write" + "" + "code";
2. alert(hobby) //I love to write code
There are also bitwise operators which are supported in other programming languages too. They are: AND(&), OR(|), XOR(^), NOT(~), LEFT SHIFT (<<), RIGHT SHIFT (>>) , ZERO-FILL SHIFT(>>>)
Comma: The comma operator is used to evaluate multiple expressions separated by a comma. You will only get the result of the last operation after evaluating.
1. let a = (2 +3, 4+5) ;
2. alert(a); //9 (the result of 4 + 5)
Comparison
Comparison in JavaScript is similar to mathematical comparison. Let's have a look:
Greater than / less than : x > y, x < y Greater / less than or equals : x >= y, x <= y Equals x == y; ( single = is for assignment not comparison) Not equal to : x != y
When you compare values, you get Boolean as the result.
1. alert(100 > 10); // true (correct)
2. alert(100 < 10); // false (wrong)
3. alert(100 != 10); // true (correct)
Strings can also be compared in JavaScript. They are compared letter-by-letter in lexicographical order.
1. alert("B" > "A"); true
2. alert("apple" > "ball"); //false ( the first alphabet 'a' is less than 'b')
Type comparison
When you compare the value of different types, JavaScript converts them to numbers.
alert("10" > 1); //true, the string "10" gets converted to a number 10
Strict equality(===) Regular equality (==) converts operands of different types to numbers. The issue with this is that 0 cannot be differentiated from false.
alert(0 == false); //true
We also have the same conversion with an empty string.
alert(" " == false); //true, empty string is converted to 0
To avoid type conversion, it is better to use strict equality (===)
alert(0 === false); //false
Similarly, 'strict non-equality' operator !==
can be used in place of regular !=
.
Using strict equality, null and undefined are of different types.
alert(null===undefined) //false
However, using regular equality (==), null and undefined are seen as equal.
alert(null == undefined) //true
Conditionals
Just as you make decisions all the time, when you execute a code, it needs to make certain decisions to carry out specific actions correctly. That is what conditionals do. They exert control on a program.
if..else
statements are conditionals/branching statements that you use to create different paths for the execution of your code.
Usually, if
statement can stand on its own. However, else
statement must be used together with if
statement.
Syntax for if
statement:
if (condition) { // code here}
The condition is the logical expression that evaluates to a Boolean value (either true or false).
If true - code inside curly bracket will be executed. If false - code inside curly bracket will be skipped over.
When you want a code to be executed when the condition is false, you introduce an else statement.
In JavaScript, you can use else and if together with a space between them.
if (false){
// condition is false so code won't run
}else if (false){
// will else not run
} else {
//will run as final code
}
Key points:
if
statement: Is used to execute a block of code when a condition is true.
else
statement: Is used to execute a block of code when a condition is false.
else if
statement: In the case where the first condition is false, it specifies a new test.
Ternary operator '?' (If..else shorthand)
The ternary operator is shorthand for writing if..else
statements. Here's the syntax:
condition ? option A : option B;
- if the condition is true: Option A is executed
- if the condition is false: Option B is executed
Let's see an example:
1. let time = 12;
2. let greeting;
3. greeting = time <=10 ? "Hello" : "greetings";
4. alert(greeting) // Hello
Switch Statement
A switch statement is used to compare a value with multiple options.
Let's say you have a lot of if statements in your code and would like to replace them, you can use a switch statement to do so.
With switch
, you can state different options, termed as case blocks and an optional default statement.
The syntax forswitch
statement is:
switch (expression) {
case value1:
//statements
break;
case value2:
//statements
break;
case value3:
//statements
break;
default:
statements
break;
}
Notice the break
statement at the end of each case clause. This is what tells the switch statement to stop and exit. Omitting it will produce incorrect results - the switch statement will continue to run any case clause that evaluates to true.
However, when a default clause is present, you can safely omit the break statement.
Loops
Think of repeated if statements. A loop is used to iterate a piece of code. With loops, you can make a piece of code perform repeated tasks multiple times according to a stated condition.
The condition is evaluated and gives a Boolean result which is either true or false.
A loop process will continue until a false condition is returned. If the condition never returns false, then you will get what is called an infinite loop (a loop with no end). This can disrupt your system.
Loops are categorized into two groups:
- Entry loop
- Exit loop
Entry loop: When you want a program to check for a condition before execution, an entry loop is used. Examples of entry loops include for
and while
loops.
Exit loop: An exit loop checks for when to exit control in a loop. If the condition for an exit is true, the loop iteration ends. An example of an exit loop is do..while
loop.
There are different types of loops in JavaScript:
- for loop
- for...in loop
- do...while loop
- while loop
for loop
syntax is as follows:
for(initialization; condition; incrementation){
//some code here
}
initialization - is the initial value of a variable.
condition - a boolean expression that is evaluated as each loop is iterated.
implementation - an expression that is evaluated after each loop iteration.
Here's is an example of for loop
:
for(let i=0; i<5; i++){
console.log(i)
}
// output
0
1
2
3
4
Let's break down the above example, here's how it works:
A new variable, i, is initialized
x < 5 is the condition that will be evaluated before the loop runs.
If true, the statement inside the loop will run (in this case (console.log(i)).
The value of i is then incremented.
And the loop starts all over until the condition returns false (in this case, until i is no longer less than 5), then the loop exits.
while loops
while
statement creates a loop that will continue to run as long as the stated condition evaluates to true. The syntax is as follow:
while(condition){
// execute this code
}
Functions
A function is a bit of reusable code written in order to reduce code repetition.
When you want to handle a particular task in your program, you can write a function for it. So it's just like a mini-program within your main program.
In this article, we have used some built-in functions like alert()
, prompt()
, and confirm()
. JavaScript has a number of them you can utilize when writing your code.
Interestingly, you can write your own functions to handle different tasks in your program.
Here's a basic step to follow:
- Declare the function: You declare the function using the
function
keyword.
function nameOfFunction(){
//some code here
}
- Call the function: To get the function to run, you have to invoke it by calling it like this:
nameOfFunction();
Here's an example:
// declare a function
1. function greeting(){
alert("Hey there!");
return;
};
// call the function
2. greeting(); //Hey there
return
is a directive that sends back a value to the function after executing the code within the function.
Notice the function declaration consist of the following in this order:
Function keyword
Name of the function
Parentheses (this can either be empty or may contain one or more parameters)
Pair of curly brackets that contain the code (function body).
A parameter is data you pass to a function when you declare the function"
Here's the syntax for defining a parameter:
function nameOfFunction(parameter){
//some code here
}
An argument is the value of the parameter you pass to the function when you call it"
Here's a syntax for defining an argument:
nameOfFunction(argument)
Function Expressions
A function can be written in more than one way and function expression is just of the ways.
When writing a function expression, the function name is omitted to create an anonymous function.
Here's an example of a function expression:
// declare an anonymous function and assign to a variable
let anotherFunction = function(){
//some code here
}
Arrow function
This is another way to write a function but a shorter syntax. Arrow function was introduced in ES6. Here is the syntax:
let nameOfFunction = (argument) => {
//expression
}
They can be written with or without curly brackets. A curly bracket is used when there are multiple statements inside the function. In this case, the return keyword must be included.
To wrap up, here's a list of resources that could further aid your learning.
JavaScript is a broad and interesting language to learn. And a grasp of these fundamentals will ace your learning journey.
That's all for this piece. Happy coding :)