PRO 30% Free • Stripe ($15) & Razorpay (₹899)

JavaScript Glossary

Top Course Staff · 7 min read · Web development · PRO · 30% Free Preview Available

JavaScript Glossary

Update: Cheat Sheets BETA is here!

  • Introduction toJavaScript:Introduction
  • Introduction to JavaScript:Conditionals
  • Introduction to JavaScript:Functions
  • Introduction to JavaScript:Scope

Arrays

Accessing array elements

You can get elements out of arrays if you know their index. Array elements’ indices start at 0 and increment by 1, so the first element’s index is 0, the second element’s index is 1, the third element’s index is 2, etc.

Syntax

array[index];
Copy to clipboard
array[index];

Example

var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];primes[0]; // 2primes[3]; // 7primes[150]; // undefined
Copy to clipboard
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];primes[0]; // 2primes[3]; // 7primes[150]; // undefined

Array literals

You can create arrays in two different ways. The most common of which is to list values in a pair of square brackets. JavaScript arrays can contain any types of values and they can be of mixed types.

const arrayName = [element0, element1, ..., elementN]
Copy to clipboard
const arrayName = [element0, element1, ..., elementN]
const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];
Copy to clipboard
const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37];

Read more

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Multi-dimensional Arrays

A two-dimensional array is an array within an array. If you fill this array with another array you get a three-dimensional array and so on.

// Two dimensions, 3x3const multidimensionalArray = [[1,2,3],[4,5,6],[7,8,9]]
Copy to clipboard
// Two dimensions, 3x3const multidimensionalArray = [[1,2,3],[4,5,6],[7,8,9]]

Array constructor

You can also create an array using the Array constructor.

const stuff = new Array();
stuff[0] = 34;stuff[4] = 20;
stuff;// [34, undefined, undefined, undefined, 20]
Copy to clipboard
const stuff = new Array();
stuff[0] = 34;stuff[4] = 20;
stuff;// [34, undefined, undefined, undefined, 20]
const myArray = new Array(45 , 'Hello World!' , true , 3.2 , undefined);console.log(myArray);
// output: [ 45, 'Hello World!', true, 3.2, undefined ]
Copy to clipboard
const myArray = new Array(45 , 'Hello World!' , true , 3.2 , undefined);console.log(myArray);
// output: [ 45, 'Hello World!', true, 3.2, undefined ]
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Example.3A_Creating_an_array

Accessing nested array elements

Accessing multi-dimensional array elements is quite similar to one-dimension arrays. They are accessed by using [index][index]….. (number of them depends upon the number of arrays deep you want to go inside).

array[index][index] //...
Copy to clipboard
array[index][index] //...
const myMultiArray = [  [1, 2, 3, 4, 5, [1, 2, 3, 4, 5] ],  [6, 7, 8, 9, 10, [1, 2, 3, 4, 6] ],  [11, 12, 13, 14, 15, [1, 2, 3, 4, 5] ],  [16, 17, 18, 19, 20, [1, 2, 3, 4, 5] ]];
console.log(myMultiArray[1][5][4]);// Outputs 6, the value in the last element of the last element of the second element of myMultiArray.
Copy to clipboard
const myMultiArray = [  [1, 2, 3, 4, 5, [1, 2, 3, 4, 5] ],  [6, 7, 8, 9, 10, [1, 2, 3, 4, 6] ],  [11, 12, 13, 14, 15, [1, 2, 3, 4, 5] ],  [16, 17, 18, 19, 20, [1, 2, 3, 4, 5] ]];
console.log(myMultiArray[1][5][4]);// Outputs 6, the value in the last element of the last element of the second element of myMultiArray.

Booleans

Boolean literals

truefalse
Copy to clipboard
truefalse

Boolean logical operators

expression1 && expression2// Returns true if both the expressions evaluate to true
expression3 || expression4// Returns true if either one of the expression evaluates to true
!expression5// Returns the opposite boolean value of the expression
Copy to clipboard
expression1 && expression2// Returns true if both the expressions evaluate to true
expression3 || expression4// Returns true if either one of the expression evaluates to true
!expression5// Returns the opposite boolean value of the expression
if (true && false) {;  // This block is not entered because the second expression is false}
if (false || true) {  // This block is entered because any one of the expression is true}
if (!false) {  // This block is entered because !false evaluates to true}
!!true // Evaluates to true
Copy to clipboard
if (true && false) {;  // This block is not entered because the second expression is false}
if (false || true) {  // This block is entered because any one of the expression is true}
if (!false) {  // This block is entered because !false evaluates to true}
!!true // Evaluates to true
if (!false && ( false || (false && true) )) {  console.log('Guess what...');}
/* Not executed because !false && ( false || (false && true) ) - becomes!false && ( false || false) - becomestrue && false , which is false.*/
Copy to clipboard
if (!false && ( false || (false && true) )) {  console.log('Guess what...');}
/* Not executed because !false && ( false || (false && true) ) - becomes!false && ( false || false) - becomestrue && false , which is false.*/
/* An important thing to note here is the Operator Precedence - which determines the order in which operators are evaluated. Operators with higher precedence are evaluated first. Thus among the four - () , && , || , ! */
// Brackets - have the highest precedence// ! - lower than Brackets// && - lower than !// || - the lowest
if (true && !!false || true) {  console.log('Guess again ??');}
/* Executed , here is the evaluation process-true && !!false || true - becomestrue && false || true - (no brackets present , so ! evaluated ) becomesfalse || true - (then && evaluated) which becomes true */
Copy to clipboard
/* An important thing to note here is the Operator Precedence - which determines the order in which operators are evaluated. Operators with higher precedence are evaluated first. Thus among the four - () , && , || , ! */
// Brackets - have the highest precedence// ! - lower than Brackets// && - lower than !// || - the lowest
if (true && !!false || true) {  console.log('Guess again ??');}
/* Executed , here is the evaluation process-true && !!false || true - becomestrue && false || true - (no brackets present , so ! evaluated ) becomesfalse || true - (then && evaluated) which becomes true */
/* Next important thing is the Associativity - which determines the order in which operators of the same precedence are processed. For example, consider an expression: a * b * c. Left-associativity (left-to-right) means that it is processed as (a * b) * c, while right-associativity (right-to-left) means it is interpreted as a * (b * c). */
// Brackets , && , || have left to right associativity // ! has right to left associativity
!false && !!false // false// evaluated in the manner - !false && false - true && false - false
Copy to clipboard
/* Next important thing is the Associativity - which determines the order in which operators of the same precedence are processed. For example, consider an expression: a * b * c. Left-associativity (left-to-right) means that it is processed as (a * b) * c, while right-associativity (right-to-left) means it is interpreted as a * (b * c). */
// Brackets , && , || have left to right associativity // ! has right to left associativity
!false && !!false // false// evaluated in the manner - !false && false - true && false - false

Comparison operators

x === y // Returns true if two things are equalx !== y // Returns true if two things are not equalx <= y // Returns true if x is less than or equal to yx >= y // Returns true if x is greater than or equal to yx < y // Returns true if x is less than yx > y // Returns true if x is greater than y
Copy to clipboard
x === y // Returns true if two things are equalx !== y // Returns true if two things are not equalx <= y // Returns true if x is less than or equal to yx >= y // Returns true if x is greater than or equal to yx < y // Returns true if x is less than yx > y // Returns true if x is greater than y

“Truthy” and “Falsy”

Only Boolean literals (trueandfalse) assert truth or false, but there are some other ways too to derive true or false. Have a look at the examples.

if (1) {  // Output 'True!', since any non-zero number is considered to be true  console.log('True!');}
if (0) {  // Not executed, since 0 evaluates to falsy  console.log('I doubt if this gets executed');}
if ('Hello') {  // Gets executed because non-empty strings are truthy  console.log('So, any non-empty String is also true.'); }
if ('') {  // Not executed  console.log('Hence , an empty String is false');}
Copy to clipboard
if (1) {  // Output 'True!', since any non-zero number is considered to be true  console.log('True!');}
if (0) {  // Not executed, since 0 evaluates to falsy  console.log('I doubt if this gets executed');}
if ('Hello') {  // Gets executed because non-empty strings are truthy  console.log('So, any non-empty String is also true.'); }
if ('') {  // Not executed  console.log('Hence , an empty String is false');}
  • https://developer.mozilla.org/en-US/docs/Glossary/Falsy
  • https://developer.mozilla.org/en-US/docs/Glossary/Truthy

==vs.===

A simple explanation would be that==does just value checking (no type checking ), whereas,===does both value checking and type checking. Seeing the examples may make it all clear. It is always advisable that you never use==, because==often produces unwanted results.

expression == expressionexpression === expression
Copy to clipboard
expression == expressionexpression === expression
'1' == 1  // true (same value)'1' === 1 // false (not the same type)
true == 1  // true (because 1 evaluates as truthy, though it's not the same type)true === 1 // false (not the same type)
Copy to clipboard
'1' == 1  // true (same value)'1' === 1 // false (not the same type)
true == 1  // true (because 1 evaluates as truthy, though it's not the same type)true === 1 // false (not the same type)

Code Comments

Code comments are used for increasing the readability of the code.If you write 100 lines of code and then forget what each function did, it’s not useful at all. Comments are like notes, suggestions, warnings, etc. that you can put for yourself. Code comments are not executed

Single Line Comment

Anything on the line following//will be a comment while anything before will still be code.

console.log('This code will be run');// console.log('Because this line is in a comment, this code will not be run.')// This is a single line comment.
Copy to clipboard
console.log('This code will be run');// console.log('Because this line is in a comment, this code will not be run.')// This is a single line comment.

Multi-Line Comment

Anything between/*and*/will be a comment.

/* This is   a multi-line

   comment!*/
Copy to clipboard
/* This is   a multi-line

   comment!*/
/* console.log('Hello,I won't be executed.');console.log('Hello ,I also will not be executed');*/
Copy to clipboard
/* console.log('Hello,I won't be executed.');console.log('Hello ,I also will not be executed');*/

Console

console.log

Prints text to the console. Useful for debugging.

const name = 'Codecademy';console.log(name);
Copy to clipboard
const name = 'Codecademy';console.log(name);

console.time

This function starts a timer which is useful for tracking how long an operation takes to happen.You give each timer a unique name, and may have up to 10,000 timers running on a given page.When you callconsole.timeEnd()with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.

console.time(timerName);
Copy to clipboard
console.time(timerName);
console.time('My Math');const x = 5 + 5;console.log(x);console.timeEnd('My Math');console.log('Done the math.');
/* Output:10My Math: (time taken)Done the math.*/
Copy to clipboard
console.time('My Math');const x = 5 + 5;console.log(x);console.timeEnd('My Math');console.log('Done the math.');
/* Output:10My Math: (time taken)Done the math.*/
  • https://developer.mozilla.org/en-US/docs/Web/API/console.time
  • https://developer.mozilla.org/en-US/docs/Web/API/console.timeEnd

console.timeEnd()

Stops a timer that was previously started by callingconsole.time().

console.timeEnd(timerName);
Copy to clipboard
console.timeEnd(timerName);
console.time('My Math');const x = 5 + 5;console.log(x);console.timeEnd('My Math');
/* Output :10My Math: (time taken)*/
Copy to clipboard
console.time('My Math');const x = 5 + 5;console.log(x);console.timeEnd('My Math');
/* Output :10My Math: (time taken)*/
  • https://developer.mozilla.org/en-US/docs/Web/API/console.timeEnd

A function is a JavaScript procedure—a set of statements that performs a task or calculates a value.It is like a reusable piece of code. Imagine , having 20 for loops ,and then having a single function to handle it all . To use a function, you must define it somewhere in the scope from which you wish to call it. A function definition (also called a function declaration) consists of the function keyword, followed by the name of the function, a list of arguments to the function, enclosed in parentheses and separated by commas, the JavaScript statements that define the function, enclosed in curly braces,{ }.

function name(argument1 , argument2, /* ..., argumentN */){  statement1;  statement2;  // ...   statementN;} 
Copy to clipboard
function name(argument1 , argument2, /* ..., argumentN */){  statement1;  statement2;  // ...   statementN;}
function greet(name) {  return 'Hello' + name + '!';}
Copy to clipboard
function greet(name) {  return 'Hello' + name + '!';}
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

Function calling

functionName(argument1, argument2, ..., argumentN);
Copy to clipboard
functionName(argument1, argument2, ..., argumentN);
greet('Anonymous');// Hello Anonymous!
Copy to clipboard
greet('Anonymous');// Hello Anonymous!

Function hoisting

The two ways of declaring functions produce different results. Declaring a function one way “hoists” it to the top of the call, and makes it available before it’s actually defined.

hoistedFunction(); // Hello! I am defined immediately!notHoistedFunction(); // ReferenceError: notHoistedFunction is not defined
function hoistedFunction () {  console.log('Hello! I am defined immediately!');}
var notHoistedFunction = function () {  console.log('I am not defined immediately.');}
Copy to clipboard
hoistedFunction(); // Hello! I am defined immediately!notHoistedFunction(); // ReferenceError: notHoistedFunction is not defined
function hoistedFunction () {  console.log('Hello! I am defined immediately!');}
var notHoistedFunction = function () {  console.log('I am not defined immediately.');}
  • https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

It simply states that if this condition is true, do this, else do something else (or nothing). It occurs in varied forms.

// Form : Single Ifif (condition) {  // code that runs if the condition is true}
Copy to clipboard
// Form : Single Ifif (condition) {  // code that runs if the condition is true}
if (answer === 42) {  console.log('Told you so!');}
Copy to clipboard
if (answer === 42) {  console.log('Told you so!');}

else

A fallback to anifstatement. This will only get executed if the previous statement did not.

// If the condition is true, statement1 will be executed.// Otherwise, statement2 will be executed.
if (condition) {  // statement1: code that runs if condition is true} else {  // statement2: code that runs if condition is false}
Copy to clipboard
// If the condition is true, statement1 will be executed.// Otherwise, statement2 will be executed.
if (condition) {  // statement1: code that runs if condition is true} else {  // statement2: code that runs if condition is false}
if (animal == 'dog') {  console.log('Bark, bark!');} else {  console.log('Meow!');}
Copy to clipboard
if (animal == 'dog') {  console.log('Bark, bark!');} else {  console.log('Meow!');}

else if

This is like anelsestatement, but with its own condition. It will only run if its condition is true, and the previous statement’s condition was false.

// Form : else if. If the condition is true, statement1 will be executed. Otherwise, condition2 is checked. if it is true, then statement2 is executed. Else, if nothing is true, statement3 is executed.if (condition1) {  statement1;} else if (condition2) {  statement2;} else {  statement3;}
Copy to clipboard
// Form : else if. If the condition is true, statement1 will be executed. Otherwise, condition2 is checked. if it is true, then statement2 is executed. Else, if nothing is true, statement3 is executed.if (condition1) {  statement1;} else if (condition2) {  statement2;} else {  statement3;}
if (someNumber > 10) {  console.log('Numbers larger than 10 are not allowed.');} else if (someNumber < 0) {  console.log('Negative numbers are not allowed.');} else {  console.log('Nice number!');}
Copy to clipboard
if (someNumber > 10) {  console.log('Numbers larger than 10 are not allowed.');} else if (someNumber < 0) {  console.log('Negative numbers are not allowed.');} else {  console.log('Nice number!');}

For Loops

You useforloops, if you know how often you’ll loop. The most often used varName in loops isi.

for ([let i = startValue]; [i < endValue]; [i+=stepValue]) {  // Loop code here}
Copy to clipboard
for ([let i = startValue]; [i < endValue]; [i+=stepValue]) {  // Loop code here}
for (let i = 0; i < 5; i++) {  console.log(i); // Prints the numbers from 0 to 4}
Copy to clipboard
for (let i = 0; i < 5; i++) {  console.log(i); // Prints the numbers from 0 to 4}
let i;  // 'outsourcing' the definitionfor (i = 10; i >= 1; i--) {    console.log(i); // Prints the numbers from 10 to 1}
Copy to clipboard
let i;  // 'outsourcing' the definitionfor (i = 10; i >= 1; i--) {    console.log(i); // Prints the numbers from 10 to 1}
/* Note that all of the three statements are optional, i.e. , */let i = 9;// This loop is perfectly valid:for(;;){    if(i === 0) {      break;    }    console.log(i);    i--;}
Copy to clipboard
/* Note that all of the three statements are optional, i.e. , */let i = 9;// This loop is perfectly valid:for(;;){    if(i === 0) {      break;    }    console.log(i);    i--;}

While Loops

You usewhileloops, if you don’t know how often you’ll loop.

while (condition) {  // Your code here}
Copy to clipboard
while (condition) {  // Your code here}
let x = 0;while (x < 5) {  console.log(x); // Prints numbers from 0 to 4  x++;}
Copy to clipboard
let x = 0;while (x < 5) {  console.log(x); // Prints numbers from 0 to 4  x++;}
let x = 10;while (x <= 5) {    console.log(x); // Won't be executed    x++;}
Copy to clipboard
let x = 10;while (x <= 5) {    console.log(x); // Won't be executed    x++;}
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while

Do While Loops

You use do while loops, if you have to loop at least once, but if you don’t know how often.

do {  // Your code here} while (condition);
Copy to clipboard
do {  // Your code here} while (condition);
let x = 0;do {    console.log(x);  // Prints numbers from 0 to 4    x++;} while (x < 5);
Copy to clipboard
let x = 0;do {    console.log(x);  // Prints numbers from 0 to 4    x++;} while (x < 5);
let x = 10;do {    console.log(x); // Prints 10    x++;} while (x <= 5);
Copy to clipboard
let x = 10;do {    console.log(x); // Prints 10    x++;} while (x <= 5);
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while

.random()

Returns a random number between 0 and 1.

Math.random()
Copy to clipboard
Math.random()
Math.random(); // A random number between 0 and 1.
Copy to clipboard
Math.random(); // A random number between 0 and 1.

.floor()

Returns the largest integer less than or equal to a number.

Math.floor(expression)
Copy to clipboard
Math.floor(expression)
Math.floor(9.99); // 9Math.floor(1 + 0.5); // 1Math.floor(Math.random() * x + 1); // Returns a random number between 1 and x
Copy to clipboard
Math.floor(9.99); // 9Math.floor(1 + 0.5); // 1Math.floor(Math.random() * x + 1); // Returns a random number between 1 and x

.pow()

Returns base raised to exponent.

Math.pow(base, exponent)
Copy to clipboard
Math.pow(base, exponent)
Math.pow(2,4); // gives 16
Copy to clipboard
Math.pow(2,4); // gives 16
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow

.ceil()

Returns the smallest integer greater than or equal to a number.

Math.ceil(expression)
Copy to clipboard
Math.ceil(expression)
Math.ceil(45.4); // 46Math.ceil(4 - 1.9); // 3
Copy to clipboard
Math.ceil(45.4); // 46Math.ceil(4 - 1.9); // 3
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil

.PI

Returns the ratio of the circumference of a circle to its diameter, approximately 3.14159 or in better terms, the value of PI (π). Note in syntax , we do not put()at the end ofMath.PIbecauseMath.PIis not a function.

Math.PI
Copy to clipboard
Math.PI
Math.round(Math.PI); // rounds the value of PI ,gives 3Math.ceil(Math.PI); // 4
Copy to clipboard
Math.round(Math.PI); // rounds the value of PI ,gives 3Math.ceil(Math.PI); // 4
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI

.sqrt()

Returns the square root of a number.

Math.sqrt(expression)
Copy to clipboard
Math.sqrt(expression)
Math.sqrt(5+4); // 3Math.sqrt(Math.sqrt(122+22) + Math.sqrt(16)); // 4
Copy to clipboard
Math.sqrt(5+4); // 3Math.sqrt(Math.sqrt(122+22) + Math.sqrt(16)); // 4
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sqrt

It returns the remainder left after dividing the left hand side with the right hand side.

number1 % number2
Copy to clipboard
number1 % number2
14 % 9 // returns 5
Copy to clipboard
14 % 9 // returns 5

isNaN()

Returns true if the given number is not a number, else returns false.

isNaN([value])
Copy to clipboard
isNaN([value])
const userInput = prompt('Enter a number'); // "Enter a number"
if (isNaN(userInput)) {  console.log('I told you to enter a number.');}
// console.log executed since 'a number' is not a number
// Another important thing:
if (isNaN('3')) {  console.log('bad');}
// Not executed because the string "3" gets converted into 3, and 3 is a number
Copy to clipboard
const userInput = prompt('Enter a number'); // "Enter a number"
if (isNaN(userInput)) {  console.log('I told you to enter a number.');}
// console.log executed since 'a number' is not a number
// Another important thing:
if (isNaN('3')) {  console.log('bad');}
// Not executed because the string "3" gets converted into 3, and 3 is a number

Basic Arithmetic

Doing basic arithmetic is simple.

4 + 5;  // 94 * 5;  // 205 - 4;  // 120 / 5; // 4
Copy to clipboard
4 + 5;  // 94 * 5;  // 205 - 4;  // 120 / 5; // 4

Prefix and Postfix increment/decrement operators

Prefix increment / decrement operators are operators that first increase the value of the variable by 1 (increment) or decrease the value of an expression / variable by 1 (decrement) and then return this incremented / decremented value. They are used like++(variable) [increment] or--(varaible) [decrement] On the other hand , Postfix increment / decrement operators are operators that first return the value of the variable and then increase the value of that variable by 1 (increment) or decrease the value of the variable by 1 (decrement) . They are used like (variable)++[increment] or (varaible)--[decrement].

// Prefix Decrement:--variable// Prefix Increment:++variable// Postfix Decrement:variable--// Postfix Increment:variable++
Copy to clipboard
// Prefix Decrement:--variable// Prefix Increment:++variable// Postfix Decrement:variable--// Postfix Increment:variable++
// The examples will make it clear
let x = 15; // x has a value of 15const y = x++;// since it is postfix , the value of x (15) is first assigned to y and then the value of x is incremented by 1console.log(y); // 15console.log(x); // 16
let a = 15; // a has a value of 15const b = ++a;// since it is prefix , the value of a (15) is first incremented by 1 and then the value of x is assigned to bconsole.log(b); // 16console.log(a); // 16
Copy to clipboard
// The examples will make it clear
let x = 15; // x has a value of 15const y = x++;// since it is postfix , the value of x (15) is first assigned to y and then the value of x is incremented by 1console.log(y); // 15console.log(x); // 16
let a = 15; // a has a value of 15const b = ++a;// since it is prefix , the value of a (15) is first incremented by 1 and then the value of x is assigned to bconsole.log(b); // 16console.log(a); // 16

Object Literals

{  'property 1': value1,  property2: value2,  number: value3}
Copy to clipboard
{  'property 1': value1,  property2: value2,  number: value3}
var obj = {  name: 'Bob',  married: true,  'mother\'s name': 'Alice',  'year of birth': 1987,  getAge: function () {    return 2012 - obj['year of birth'];  },  1: 'one'};
Copy to clipboard
var obj = {  name: 'Bob',  married: true,  'mother\'s name': 'Alice',  'year of birth': 1987,  getAge: function () {    return 2012 - obj['year of birth'];  },  1: 'one'};

Property Access

name1[string]name2.identifier
Copy to clipboard
name1[string]name2.identifier
obj['name'];  // 'Bob'obj.name;     // 'Bob'obj.getAge(); // 24
Copy to clipboard
obj['name'];  // 'Bob'obj.name;     // 'Bob'obj.getAge(); // 24

Classes

A class can be thought of as a template to create many objects with similar qualities. Classes are a fundamental component of object-orientedprogramming(OOP).

SubClass.prototype = new SuperClass();
Copy to clipboard
SubClass.prototype = new SuperClass();
const Lieutenant = function (age) {  this.rank = 'Lieutenant';  this.age = age;};
Lieutenant.prototype = new PoliceOfficer();
Lieutenant.prototype.getRank = function () {  return this.rank;};
const John = new Lieutenant(67);
John.getJob(); // 'Police Officer'John.getRank(); // 'Lieutenant'John.retire(); // true
Copy to clipboard
const Lieutenant = function (age) {  this.rank = 'Lieutenant';  this.age = age;};
Lieutenant.prototype = new PoliceOfficer();
Lieutenant.prototype.getRank = function () {  return this.rank;};
const John = new Lieutenant(67);
John.getJob(); // 'Police Officer'John.getRank(); // 'Lieutenant'John.retire(); // true

alert

Display an alert dialog with the specified message and an OK button. The alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgment of the message.

alert(message);
Copy to clipboard
alert(message);
alert('Hello World');
Copy to clipboard
alert('Hello World');

confirm

Displays a dialog with the specified message and two buttons, OK and Cancel.

confirm('message') // Returns true if confirmed, false otherwise
Copy to clipboard
confirm('message') // Returns true if confirmed, false otherwise
if (confirm('Are you sure you want to delete this post?')) {  deletePost();}
Copy to clipboard
if (confirm('Are you sure you want to delete this post?')) {  deletePost();}
  • https://developer.mozilla.org/en-US/docs/Web/API/window.confirm

prompt

Theprompt()displays a dialog with an optional message prompting the user to input some text. If the user clicks the “Cancel” button, null is returned.

prompt(message);
Copy to clipboard
prompt(message);
var name = prompt('Enter your name:');console.log('Hello ' + name + '!');
Copy to clipboard
var name = prompt('Enter your name:');console.log('Hello ' + name + '!');
  • https://developer.mozilla.org/en-US/docs/Web/API/window.prompt

Strings are text. They are denoted by surrounding text with either single or double quotes.

"string of text"'string of text'
Copy to clipboard
"string of text"'string of text'

Concatenation

string1 + string2
Copy to clipboard
string1 + string2
'some' + 'text'; // returns 'sometext'const first = 'my';const second = 'string';const union = first + second; // union variable is the string 'mystring'
Copy to clipboard
'some' + 'text'; // returns 'sometext'const first = 'my';const second = 'string';const union = first + second; // union variable is the string 'mystring'

.length

Returns the length of the string.

string.length
Copy to clipboard
string.length
'My name'.length // 7 , white space is also counted''.length // 0
Copy to clipboard
'My name'.length // 7 , white space is also counted''.length // 0

.toUpperCase(),.toLowerCase()

Changes the cases of all the alphabetical letters in the string.

'my name'.toUpperCase(); // Returns 'MY NAME''MY NAME'.toLowerCase(); // Returns 'my name'
Copy to clipboard
'my name'.toUpperCase(); // Returns 'MY NAME''MY NAME'.toLowerCase(); // Returns 'my name'

.trim()

Removes whitespace from both ends of the string.

string.trim()
Copy to clipboard
string.trim()
'       a        '.trim(); // 'a''     a  a       '.trim(); // 'a  a'
Copy to clipboard
'       a        '.trim(); // 'a''     a  a       '.trim(); // 'a  a'
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

.replace()

Returns a string with the first match substring replaced with a new substring.

'original string'.replace('original', 'replaced'); // returns 'replaced string'
Copy to clipboard
'original string'.replace('original', 'replaced'); // returns 'replaced string'

.charAt()

Returns the specified character from a string. Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string calledstringNameisstringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string.

string.charAt(index) // index is an integer between 0 and 1 less than the length of the string.
Copy to clipboard
string.charAt(index) // index is an integer between 0 and 1 less than the length of the string.
'Hello World!'.charAt(0); // 'H''Hello World!'.charAt(234); // ''
Copy to clipboard
'Hello World!'.charAt(0); // 'H''Hello World!'.charAt(234); // ''
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt

.substring()

Returns the sequence of characters between two indices within a string.

string.substring(indexA[, indexB])// indexA : An integer between 0 and the length of the string// indexB : (optional) An integer between 0 and the length of the string.
Copy to clipboard
string.substring(indexA[, indexB])// indexA : An integer between 0 and the length of the string// indexB : (optional) An integer between 0 and the length of the string.
'adventures'.substring(2,9); // Returns 'venture'// substring starts from indexA(2) , and goes up to but not including indexB(9)'hello'.substring(1); // returns 'ello''Web Fundamentals'.substring(111); // returns '''In the market'.substring(2,999); // returns ' the market''Fast and efficient'.substring(3,3); // returns '''Go away'.substring('abcd' , 5); // returns 'Go aw'// Any non-numeric thing is treated as 0
Copy to clipboard
'adventures'.substring(2,9); // Returns 'venture'// substring starts from indexA(2) , and goes up to but not including indexB(9)'hello'.substring(1); // returns 'ello''Web Fundamentals'.substring(111); // returns '''In the market'.substring(2,999); // returns ' the market''Fast and efficient'.substring(3,3); // returns '''Go away'.substring('abcd' , 5); // returns 'Go aw'// Any non-numeric thing is treated as 0

.indexOf()

Returns the index within the calling String object of the first occurrence of the specified value, starting the search atfromIndex, Returns-1if the value is not found. The.indexOf()method is case sensitive.

string.indexOf(searchValue[, fromIndex]) // fromIndex is optional. It specifies from which index should the search start.Its default value is 0.
Copy to clipboard
string.indexOf(searchValue[, fromIndex]) // fromIndex is optional. It specifies from which index should the search start.Its default value is 0.
'My name is very long.'.indexOf('name'); // returns 3'My name is very long.'.indexOf('Name'); // returns -1 , it's case sensitive'Where are you going?'.indexOf('are', 11); //returns -1'Learn to Code'.indexOf(''); //returns 0 'Learn to Code'.indexOf('', 3); //returns 3'Learn to Code'.indexOf('', 229); returns 13 , which is the string.length
Copy to clipboard
'My name is very long.'.indexOf('name'); // returns 3'My name is very long.'.indexOf('Name'); // returns -1 , it's case sensitive'Where are you going?'.indexOf('are', 11); //returns -1'Learn to Code'.indexOf(''); //returns 0 'Learn to Code'.indexOf('', 3); //returns 3'Learn to Code'.indexOf('', 229); returns 13 , which is the string.length
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

Acts like a big if / else if / else chain. Checks a value against a list of cases, and executes the first case that is true. It goes on executing all other cases it finds after the first true case till it finds a breaking statement, after which it breaks out of the switch If it does not find any matching case, it executes the default case.

switch (expression) {  case label1:    statements1;    // break;  case label2    statements2;    // break;  ...  case labelN:    statementsN;    // break;  default:    defaultStatement;    // break;}
Copy to clipboard
switch (expression) {  case label1:    statements1;    // break;  case label2    statements2;    // break;  ...  case labelN:    statementsN;    // break;  default:    defaultStatement;    // break;}
const weather = "clear";
switch (weather) {  case 'clear':    console.log("Beautiful day!");  case 'cloudy':    console.log('I wish the sun were out!');  default:    console.log('Some weather, huh?');}
// Because there are no breaks, all three statements will be logged
Copy to clipboard
const weather = "clear";
switch (weather) {  case 'clear':    console.log("Beautiful day!");  case 'cloudy':    console.log('I wish the sun were out!');  default:    console.log('Some weather, huh?');}
// Because there are no breaks, all three statements will be logged

The ternary operator is usually used as a shortcut for the if statement.

condition ? expr1 : expr2
Copy to clipboard
condition ? expr1 : expr2
const grade = 85;console.log('You ' + (grade > 50 ? 'passed!' : 'failed!'));
//Output: You passed!
/* The above statement is same as saying:if(grade > 50){  console.log('You ' + 'passed!');  // or simply 'You passed!'}else{    console.log('You ' + 'failed!'); }*/
Copy to clipboard
const grade = 85;console.log('You ' + (grade > 50 ? 'passed!' : 'failed!'));
//Output: You passed!
/* The above statement is same as saying:if(grade > 50){  console.log('You ' + 'passed!');  // or simply 'You passed!'}else{    console.log('You ' + 'failed!'); }*/

Variable Assignment

var name = value;
Copy to clipboard
var name = value;
var x = 1;var myName = 'Bob';var hisName = myName;
Copy to clipboard
var x = 1;var myName = 'Bob';var hisName = myName;

ES6constandlet

// let variables can be reassignedlet message = 'I can be reassigned!';// const variables cannot be reassignedconst message2 = 'I cannot be reassigned';
Copy to clipboard
// let variables can be reassignedlet message = 'I can be reassigned!';// const variables cannot be reassignedconst message2 = 'I cannot be reassigned';

Scope

letandconstare both scoped to the block in which they are initialized. This can be a smaller scope thanvarvariables, which are scoped to the function in which they are initialized.

const dog = true;if (dog) {  let mood = 'happy'}console.log(mood)// Error! mood is scoped to the if block, so it is not defined outside that block.
Copy to clipboard
const dog = true;if (dog) {  let mood = 'happy'}console.log(mood)// Error! mood is scoped to the if block, so it is not defined outside that block.

Variable Reassignment

varname = newValue
Copy to clipboard
varname = newValue
// Declare variable and give it value of 'Michael'let name = 'Michael'// Change the value of name to 'Samuel'name = 'Samuel'
Copy to clipboard
// Declare variable and give it value of 'Michael'let name = 'Michael'// Change the value of name to 'Samuel'name = 'Samuel'

constvariables cannot be reassigned and attempting to do so will throw aTypeError:

// Declare variable and give it value of 'Michael'const name = 'Michael'// Try changing the value of name to 'Samuel'name = 'Samuel'// Throws:// TypeError: Assignment to constant variable.
Copy to clipboard
// Declare variable and give it value of 'Michael'const name = 'Michael'// Try changing the value of name to 'Samuel'name = 'Samuel'// Throws:// TypeError: Assignment to constant variable.

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

30% Free Preview Reached · Unlock Remaining 70%

Complete Payment to Unlock Full Guide & Source Code

You are viewing the 30% preview. Join TopCourseAI Pro to unlock the remaining 70% of this article, unblur all code snippets, and gain full access to all 412 technical projects and guides.

✓ Full Access to All 160+ Projects
✓ Instant Blur Removal Everywhere
✓ Production Source Code & Blueprints
✓ All Future Deep Dives Included
Instant Unhindered Activation ·
End of Preview · Unlock Complete Blueprint & Source Code

Ready to access the complete step-by-step tutorial?

Gain full unhindered access to all 412 technical projects and guides, unblur all source code snippets, and download runnable scripts.

Production AI Blueprints

Ready to build production-grade AI systems?

Enjoyed this guide? Continue exploring our library of 166+ production blueprints, multi-agent swarms, and autonomous agent systems with 100% unblurred, executable source code.