Basic JavaScript
Table of contents
- Comment
- Data types
- Declare Variables
- Assignment Operator (=)
- Uninitialized Variables
- Case Sensitivity in Variables
- The var and let Keywords
- Read-Only Variables (const)
- Arithmetic operators
- Assignment Operators
- Strings
- Array
- Array methods
- Function
- If Else Statements
- Switch Statements
- Objects
- While Loops
- For Loops
- Do While Loops
- Recursion
- Math.random()
- parseInt() Method
Comment
// In-line comment
/*
Multi-line
comment
*/
Data types
JavaScript provides eight different data types which are undefined, null, boolean, string, symbol, bigint, number, and object.
Declare Variables
var myName;
We can declare a variable by putting the keyword var in front of it. Statements end with semicolons. Variable names can be made up of numbers, letters, and $ or _, but may not contain spaces or start with a number.
Assignment Operator (=)
Storing Values
var a;
a = 3;
If there are any calculations to the right of the = operator, those are performed before the value is assigned to the variable on the left of the operator.
Assigning the Value of One Variable to Another
var b;
b = a;
After a value is assigned to a variable using the assignment operator, you can assign the value of that variable to another variable using the assignment operator.
Initializing Variables
var myVar = 0;
You can initialize a variable to an initial value in the same line as it is declared.
Uninitialized Variables
var undefinedVar;
When JavaScript variables are declared, they have an initial value of undefined.
var b = undefinedVar + 1;
If you do a mathematical operation on an undefined variable your result will be NaN which means "Not a Number".
b = undefinedVar + "string";
If you concatenate a string with an undefined variable, you will get a string of undefined.
Case Sensitivity in Variables
In JavaScript all variables and function names are case sensitive. It is possible to have multiple distinct variables with the same name but different casing. It is strongly recommended that for the sake of clarity, you do not use this language feature.
var someVariableName;
Best Practice: Write variable names in JavaScript in camelCase. In camelCase, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.
Note: It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays).
The var and let Keywords
var name = "James";
var name = "David";
console.log(name); // David
The var keyword can overwrite variable declarations.
let name = "James";
let name = "David";
// This results in an error.
A variable with the same name can only be declared once with the let keyword.
Read-Only Variables (const)
const MY_PET = "Dog";
MY_PET = "Cat";
// This results in an error.
The const has all the features that let has, with that variables declared using const are read-only. They are a constant value, which means that once a variable is assigned with const, it cannot be reassigned.
Arithmetic operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder (Modulus)
++ Increment
-- Decrement
** Exponentiation (ES2016)
Assignment Operators
Operator Example Same As Description
= x = y x = y Assignment Operator
+= x += y x = x + y Addition Assignment Operator
-= x -= y x = x - y Subtraction Assignment Operator
*= x *= y x = x * y Multiplication Assignment Operator
/= x /= y x = x / y Division Assignment Operator
%= x %= y x = x % y Remainder Assignment Operator
**= x **= y x = x ** y Exponentiation Assignment Operator
Strings
const name1 = "James";
const name2 = 'James';
You can use single or double quotes.
const str1 = "I'm good";
const str2 = "Her name is 'Amy'";
const str3 = 'Her name is "Amy"';
You can use quotes inside a string, as long as they don't match the quotes surrounding the string.
Length
let text = "AB CDE";
let length = text.length;
Escape sequences
Code Output
\' single quote
\" double quote
\\ backslash
\n newline
\t tab
\r carriage return
\b backspace
\f form feed
\t Horizontal Tabulator
\v Vertical Tabulator
Find the Nth Character
const firstName = "James";
const secondLetter = firstName[1]; //a
const lastLetter = firstName[firstName.length - 1]; //s
const thirdToLastLetter = firstName[firstName.length - 3]; //m
String Immutability
let name = "Bake";
name[0] = "J"; //Error
name = "Jake";
String values are immutable, which means that they cannot be altered once created. But they can be re-assigned.
Array
const sandwich = ["pasta", "pizza", "bread"];
const menu = [
["pasta", 20],
["pizza", 25],
["bread", 10]
]; // multi-dimensional array
console.log(sandwich[0]) // pasta
console.log(menu[1][0]) // pizza
An array is a variable, which can hold more than one value. It is a common practice to declare arrays with the const keyword. We can access the data inside arrays using indexes.
Array methods
push()
const arr1 = [5, 4, 3];
arr1.push(2);
console.log(arr1); // [ 5, 4, 3, 2 ]
console.log(arr1.push(1)); // 5
const arr2 = ["A", "B", "C"];
arr2.push(["D", "E"]);
console.log(arr2); // [ "A", "B", "C", [ "D", "E" ] ]
The push() method takes one or more parameters and appends data to the end of an array and returns the new length.
pop()
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.pop()); // Mango
console.log(fruits); // ["Banana", "Orange", "Apple"]
The pop() method removes the last element of an array and returns the removed element.
shift()
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.shift()); // Banana
console.log(fruits); // ["Orange", "Apple", "Mango"];
The shift() method removes the first item of an array and returns the shifted element.
unshift()
const fruits = ["Banana", "Orange"];
fruits.unshift("Lemon","Pineapple");
console.log(fruits); // ["Lemon","Pineapple", "Banana", "Orange"]
The unshift() method adds new elements to the beginning of an array.
Function
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
let x = functionName(1, 3);
function functionName(parameter1, parameter2) {
return parameter1 * parameter2;
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
When JavaScript reaches a return
statement, the function will stop executing. If the function doesn't have a return statement, it returns the undefined
value.
let text = "The product value is " + functionName(2, 2)".";
Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.
let globalVariable = "Jake"; // Global variable
function myName() {
let localVariable = "James"; // Local variable
console.log(localVariable); // James
}
console.log(globalVariable); // Jake
console.log(localVariable); // error
Inside the function, the arguments (the parameters) behave as local variables. Local variables are created when a function starts and deleted when the function is completed.
If Else Statements
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Use the if
statement to specify a block of JavaScript code to be executed if a condition is true.
if (time < 10) {
greeting = "Good morning"; // 1 <= time < 10
} else if (time < 20) {
greeting = "Good day"; // 10 <= time < 20
} else {
greeting = "Good evening"; // 20 <= time
}
Switch Statements
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Use the switch
statement to select one of many code blocks to be executed.
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
If there is no match, the default code block is executed.
let result = 0;
switch (val) {
case 1:
case 2:
case 3:
result = 1;
break;
case 4:
result = 2;
default:
result = 3;
break;
}
Objects
const profile = {
"name": "James",
"age": 32,
"pets": ["Cat", "Dogs"]
};
Objects are similar to arrays, except that instead of using indexes to access and modify their data, you access the data in objects through what are called properties(name, age, pets).
It is a common practice to declare objects with the const keyword.
const anotherObject = {
make: "Ford",
5: "five",
"model": "focus"
};
You can use numbers as properties and also omit the quotes for single-word string properties. However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.
Accessing Object Properties
const dogs = {
name: "Peter",
breed: "Doberman",
age: 5
};
const prop1val = dogs.name;
const prop2val = dogs["age"];
There are two ways to access the properties of an object: dot notation (.) and bracket notation ([])
const myDog = "breed";
const myBreed = dogs[myDog];
console.log(myBreed); // Doberman
Another use of bracket notation on objects is to access a property that is stored as the value of a variable.
dogs["age"] = 6; // Updating Object Properties
dogs.tail = 1; // Add New Properties
delete dogs.tail; // Delete New Properties
You can update, add and delete properties.
hasOwnProperty() method
function checkForProperty(object, property) {
return object.hasOwnProperty(property);
}
hasOwnProperty()
returns true or false depending on whether the property is found on the object or not.
While Loops
while (condition) {
// code block to be executed
}
The while
loop loops through a block of code as long as a specified condition is true.
For Loops
for (a; b; c) {
// code block to be executed
}
a is executed (one time) before the execution of the code block.
b defines the condition for executing the code block.
c is executed (every time) after the code block has been executed.
Do While Loops
do {
// code block to be executed
}
while (condition);
This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Recursion
function countDownFrom(number) {
if (number === 0) { //A base case
return;
}
console.log(number);
countDownFrom(number - 1);
}
countDownFrom(3);
// 3
// 2
// 1
Recursion is when a function calls itself until someone stops it.
It can be used instead of a loop.
If no one stops it, it'll recurse forever and crash your program.
A base case is a condition that stops the recursion. Don't forget to add them!
Loops use extra state variables for tracking and counting, while recursion only uses the provided parameters.
Math.random()
Math.random()
returns a random decimal number 0 <= number <1. It always returns a number lower than 1.
// Returns a random integer from 0 to 9.
Math.floor(Math.random() * 10);
// Returns a random integer from 1 to 10.
Math.floor(Math.random() * 10) + 1;
// Returns a random integer in the range from min to max.
Math.floor(Math.random() * (max - min + 1)) + min
We can use Math.floor()
to round random number down to its nearest whole number.
parseInt() Method
const a = parseInt("007"); // a = 7
The parseInt()
function parses a string and returns an integer.
If the first character in the string can't be converted into a number, then it returns NaN
.
parseInt(string, radix);
const a = parseInt("11", 2);
A radix parameter specifies the number system to use:
2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal.
The radix can be an integer between 2 and 36. If radix is omitted, JavaScript assumes radix 10. If the value begins with "0x", JavaScript assumes radix 16.
Comparison Operators
x = 5
Operator | Description | Comparing | Returns |
\== | equal to | x == 8 | false |
x == 5 | true | ||
x == "5" | true | ||
\=== | equal value and equal type | x === 5 | true |
x === "5" | false | ||
!= | not equal | x != 8 | true |
!== | not equal value or not equal type | x !== 5 | false |
x !== "5" | true | ||
x !== 8 | true | ||
\> | greater than | x > 8 | false |
< | less than | x < 8 | true |
\>= | greater than or equal to | x >= 8 | false |
<= | less than or equal to | x <= 8 | true |
Logical Operators
Operator | Description | Example | ||||
&& | and | (x < 10 && y > 1) is true | ||||
or | (x == 5 | y == 5) is false | ||||
! | not | !(x == y) is true |
Conditional (Ternary) Operator
(condition) ? first statement: second statement
function findGreater(a, b) {
return (a > b) ? "a is greater" : "b is greater or equal";
}
If the conditional statement evaluates true, the first statement will be executed. If it's false, the second statement will be executed.