JavaScript Cheat Sheet: From Basics to Advanced - IQCode (2023)

Introduction to JavaScript

JavaScript is a crucial programming language that along with HTML and CSS forms the core technologies of the World Wide Web. Around 97% of websites use JavaScript on the client-side for web page behavior, typically mixing third-party libraries. In web development, JavaScript is one of the most popular languages due to its features and capabilities.

This article provides a comprehensive JavaScript cheat sheet, along with rich documentation and how-tos, making it easy for readers to work with JavaScript. The cheat sheet aims to provide quick and correct code snippets for common scenarios. This article simplifies JavaScript for both novice and professional coders.

To test your skills and receive instant feedback and recommendations, take a free mock interview.

JavaScript Tutorial: Basics to Advanced Concepts

1. JavaScript Fundamentals

// Code goes here

Comment: Add code for JavaScript fundamentals here

Javascript Variables

In Javascript, variables are containers for storing data values. They are declared using the 'var', 'let', or 'const' keywords followed by the name of the variable. For example:

var myVariable = 10;

In this case, 'myVariable' is the name of the variable and '10' is the value being stored in it.

It is important to note that variable names are case-sensitive and can only contain letters, numbers, underscores, or dollar signs. Also, they cannot start with a number.

Furthermore, there are different scopes that variables can have in Javascript: global scope, function scope, and block scope. The scope determines where the variable can be accessed from within the code.

Javascript Data Types

In Javascript, there are six primitive data types:

  • Boolean
  • Null
  • Undefined
  • Number
  • String
  • Symbol (new in ECMAScript 6)

Additionally, there is also the Object data type, which includes arrays, functions, and more complex data structures.

Javascript Operators

Javascript operators are used to perform various actions on operands like variables, constants, and expressions. These actions can be assignment, arithmetic, comparison, logical, bitwise, and more. Here are some commonly used Javascript operators:

+

Addition operator

-

Subtraction operator

*

Multiplication operator

/

Division operator

%

Modulus operator

++

Increment operator

--

Decrement operator

=

Assignment operator

==

Equality operator

!=

Inequality operator

>

Greater than operator

<

Less than operator

>=

Greater than or equal to operator

<=

Less than or equal to operator

&&

Logical AND operator

||

Logical OR operator

!

Logical NOT operator

&

Bitwise AND operator

|

Bitwise OR operator

^

Bitwise XOR operator

~

Bitwise NOT operator

<<

Left shift operator

>>

Right shift operator

>>>

Zero-fill right shift operator

It is important to know the order of operations when using multiple operators in a single expression. Please refer to the operator precedence table in the Javascript documentation for more information.

Javascript If-Else Statements


//Example
let num1 = 10;
let num2 = 20;

if (num1 > num2) {
  console.log("Num1 is greater than Num2");
} else if (num2 > num1) {
  console.log("Num2 is greater than Num1");
} else {
  console.log("Num1 and Num2 are equal");
}

This code demonstrates the use of if-else statements in Javascript. It compares two variables and checks if num1 is greater than num2, if num2 is greater than num1, or if they are equal. The console then logs the appropriate message based on the comparison.

Javascript Functions


/*
 * Define a javascript function that takes two parameters and returns their sum.
 */
function addNumbers(num1, num2) {
  return num1 + num2;
}

/*
 * Call the function and print the result.
 */
const result = addNumbers(2, 3);
console.log(result);

In the above code, we have defined a function "addNumbers" that takes two parameters "num1" and "num2". The function returns the sum of these two parameters using the "+" operator.

We then call the function with 2 and 3 as the values for "num1" and "num2" respectively. The result is stored in a variable "result" and printed to the console using "console.log()".

Scope and Scope Chain in JavaScript


// This function demonstrates scope and scope chain in JavaScript
function outer() {
  let a = 10; // local variable 'a' declared inside 'outer' function
  function inner() {
    let b = 20; // local variable 'b' declared inside 'inner' function
    console.log(a + b); // accessing variable 'a' from outer function
  }
  inner(); // calling 'inner' function from inside 'outer' function
}
outer(); // calling 'outer' function

In JavaScript, scope refers to the visibility of variables. The scope of a variable is determined by its location in the code. Variables that are declared inside a function are called local variables and they have function-level scope. Whereas, variables that are declared outside of any function block are called global variables and they have global scope.

The concept of scope chain in JavaScript refers to how nested functions have access to variables declared in their outer functions. When a function is defined inside another function, the inner function has access to all the variables that are declared in the outer function. This access to outer function variables is possible because JavaScript follows a lexical scoping model, which means that variables are resolved based on the structure of the code.

Javascript Hoisting


  // Code examples here

Hoisting is a behavior in Javascript where variable and function declarations are moved to the top of their respective scopes at compile time, regardless of where they were declared in the code. This means that they can be accessed and used before they are declared in the code.

For example:


  console.log(x); // Outputs undefined
  var x = "Hello World!";

The code above may look like it should output an error, as x is being accessed before it is declared. However, because of hoisting, the declaration of x is moved to the top of its scope, and its value is undefined at the time of the console.log statement.

It is important to note that only the declaration of the variable or function is hoisted, not the assignment or definition. So in the previous example, the value of x is not assigned until the line where it is declared.

Hoisting can be useful in some cases, but can also lead to unexpected behavior if not understood properly. It is best practice to always declare variables and functions at the top of their respective scopes to avoid confusion and bugs in your code.

Javascript Closures

Closures are an essential concept in JavaScript, frequently used in functional programming. A closure is formed when an inner function has access to its outer function's variables, even after the outer function has finished executing.

Here is an example of a closure:

javascript
function outer() {
  let count = 0;
  function inner() {
    count++;
    console.log(count);
  }
  return inner;
}

let closureFunc = outer();
closureFunc(); // Output: 1
closureFunc(); // Output: 2
closureFunc(); // Output: 3

In this example, the `outer` function returns the `inner` function. When `outer` is called, it creates a variable `count` and a function `inner`. `inner` increments `count` and logs its value to the console.

The line `let closureFunc = outer()` calls the `outer` function and assigns the returned `inner` function to the `closureFunc` variable. When `closureFunc` is called, `count` is accessible to it because it is a closure.

Closures can be useful in many programming scenarios, such as creating private variables and functions and preventing namespace pollution.

Javascript Strings


  //Defining a string variable
  const message = "Hello, World!";

  //Using string methods
  console.log(message.toUpperCase()); //Outputs "HELLO, WORLD!"
  console.log(message.length); //Outputs 13
  console.log(message.indexOf("o")); //Outputs 4

Working with strings is a fundamental part of Javascript programming. In the example code above, we define a string variable called "message" and then use string methods to manipulate it. The

toUpperCase()

method converts all characters in the string to uppercase, while the

length

property gives us the number of characters in the string. The

indexOf()

method returns the first index at which a specified character can be found within the string.

Using the Document Object Model (DOM) in JavaScript

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. With the DOM, web developers can create and build dynamic web pages.


 // Example code that retrieves an element by its ID and changes its text content
 var element = document.getElementById("example");
 element.textContent = "This text has been changed!";

In the above code, we use the

getElementById()

method to retrieve an element with the ID of "example". We then change the text content of that element using the

textContent

property.

The DOM provides many other ways to manipulate web pages, from creating new HTML elements and attributes to removing existing ones. It is an essential part of modern web development, and any programmer working with JavaScript and HTML should have a solid understanding of how to use it.

Javascript Data Transformation


  //function to transform an array of objects
  function transformData(data) {
    let transformedData = [];
    data.forEach(item => {
      let newItem = {
        id: item.id,
        fullName: `${item.firstName} ${item.lastName}`,
        age: new Date().getFullYear() - new Date(item.dateOfBirth).getFullYear()
      };
      transformedData.push(newItem);
    });
    return transformedData;
  }

  //example usage
  let originalData = [
    {
      id: 1,
      firstName: "John",
      lastName: "Doe",
      dateOfBirth: "1990-01-01"
    },
    {
      id: 2,
      firstName: "Jane",
      lastName: "Doe",
      dateOfBirth: "1995-04-10"
    }
  ];

  let transformedData = transformData(originalData);
  console.log(transformedData);

The above code defines a function

transformData

that takes an array of objects representing people and transforms each object into a new object with properties for id, fullName, and age. The

fullName

property is a combination of the

firstName

and

lastName

properties, and the

age

property is calculated based on the

dateOfBirth

property. The function returns an array of the transformed objects.

An example usage of the function is shown, using an array of sample data to demonstrate the transformation. The output of the

transformData

function is logged to the console for verification.

JavaScript Regular Expressions

Regular expressions are a powerful tool in JavaScript for pattern matching and manipulating strings. They are defined using a specific syntax and can be used with a variety of functions and methods to search for, replace, or extract specific parts of a string.


// Example of using a regular expression to find all occurrences of a specific character in a string
let myString = "Hello World!";
let myRegex = /o/g;
let matches = myString.match(myRegex);
console.log(matches);

In this example, the regular expression /o/g is used to find all occurrences of the character "o" in the string "Hello World!". The "g" at the end of the regular expression specifies that the search should be global, meaning it will find all occurrences of the pattern in the string, not just the first one.

Regular expressions can be used in many different ways and are an essential part of any JavaScript developer's toolkit. Learning how to use them effectively can help you write more powerful and flexible code.

Numbers and Mathematics in JavaScript

In JavaScript, numbers are represented using the "number" data type. Mathematical operations can be performed using arithmetic operators such as addition (+), subtraction (-), multiplication (*), and division (/).

Example:

code
let num1 = 10;
let num2 = 5;

let sum = num1 + num2; // Addition
let difference = num1 - num2; // Subtraction
let product = num1 * num2; // Multiplication
let quotient = num1 / num2; // Division

Additionally, the modulo operator (%) can be used to find the remainder of division. For example:

code
let remainder = 10 % 3; // 1

Mathematical functions are also available in JavaScript through the built-in "Math" object. These include functions for rounding, generating random numbers, and finding the maximum or minimum value in a set of numbers.

Example:

code
let num3 = 3.75;

let roundedNum = Math.round(num3); // Round to nearest integer (4)
let randomNum = Math.random(); // Generate a random number between 0 and 1
let maxNum = Math.max(num1, num2, num3); // Find the maximum value (10)
let minNum = Math.min(num1, num2, num3); // Find the minimum value (3.75)

It is important to note that due to the way JavaScript handles numbers, certain mathematical operations may result in unexpected behavior. For example, dividing a number by 0 will return the value "Infinity" or "-Infinity" depending on the sign of the number. It is helpful to keep these quirks in mind when working with numbers in JavaScript.

Javascript Date Objects

JavaScript has a built-in Date object that allows you to work with dates and times. You can create a new Date object with the 'new' keyword followed by 'Date()', which will give you the current date and time. You can also create a Date object with a specific date and time by passing in the year, month, day, hour, minute, and second as arguments.


  // Create a new Date object with current date and time
  let currentDate = new Date();

  // Create a new Date object with specific date and time
  let specificDate = new Date(2021, 7, 21, 10, 30, 0);

You can also get various properties of a Date object, such as the year, month, day, hour, minute, and second by calling methods like 'getFullYear()', 'getMonth()', 'getDate()', 'getHours()', 'getMinutes()', and 'getSeconds()'.


  // Get year of a Date object
  let year = currentDate.getFullYear();

  // Get month of a Date object
  let month = currentDate.getMonth();

  // Get day of a Date object
  let day = currentDate.getDate();

  // Get hour of a Date object
  let hour = currentDate.getHours();

  // Get minute of a Date object
  let minute = currentDate.getMinutes();

  // Get second of a Date object
  let second = currentDate.getSeconds();

You can also set various properties of a Date object, such as the year, month, day, hour, minute, and second by calling methods like 'setFullYear()', 'setMonth()', 'setDate()', 'setHours()', 'setMinutes()', and 'setSeconds()'.


  // Set year of a Date object
  currentDate.setFullYear(2022);

  // Set month of a Date object
  currentDate.setMonth(11);

  // Set day of a Date object
  currentDate.setDate(31);

  // Set hour of a Date object
  currentDate.setHours(23);

  // Set minute of a Date object
  currentDate.setMinutes(59);

  // Set second of a Date object
  currentDate.setSeconds(59);


Javascript Browser Objects

In Javascript, browser objects refer to objects that are built into the web browser. These objects represent the elements of the web page and provide the ability to interact with them. Some common browser objects include window, document, history, location, and navigator.


// Example usage of the window object to display an alert message
window.alert("Hello World!");

By utilizing browser objects, developers can create interactive and dynamic web pages that enhance user experience. It is important for developers to have a strong understanding of these objects and their capabilities when building web applications.

JAVASCRIPT EVENTS

// This code demonstrates the usage of a JavaScript event.

// Selecting the button element const button = document.querySelector('#myButton');

// Adding event listener when the button is clicked button.addEventListener('click', function() { // Updating the text content of the paragraph element with the id 'myPara' document.getElementById('myPara').textContent = 'Button clicked!'; });

The code above shows an example of how to use a JavaScript event to update the text content of a paragraph element when a button is clicked. The button element is selected using the querySelector method and an event listener is added to it using the addEventListener method. When the button is clicked, the function passed to addEventListener is executed, which updates the text content of the paragraph element with the id 'myPara'.

Javascript Event Propagation

Code:


//select all buttons
var buttons = document.querySelectorAll('button');

//function to handle button click event
function handleClick() {
  console.log('Button clicked!');
}

//assign event handler to each button
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', handleClick);
}

Explanation: This code demonstrates how to use event propagation in Javascript to handle button click events. It starts by selecting all button elements on the page using the `document.querySelectorAll()` function. Then, it defines a function called `handleClick()` which logs a message to the console when a button is clicked. Finally, it loops through each button element and assigns the `handleClick()` function as the event handler for the `click` event using the `addEventListener()` method. This ensures that whenever a button is clicked, the message will be logged to the console.

Asynchronous JavaScript


// Example of making an asynchronous API call using JavaScript and the Fetch API

const API_URL = 'https://example.com/api/data';

// Define function to handle data from API
function handleData(data) {
  console.log(data);
  // Do something with the data
}

// Make asynchronous API call and handle response
fetch(API_URL)
  .then(response => response.json())
  .then(data => handleData(data))
  .catch(error => console.error(error.message));

Asynchronous programming in JavaScript allows programs to continue running while waiting for certain operations, such as API calls, to complete. This can greatly improve the user experience of web applications by allowing for faster page loads and responsive interfaces. The Fetch API is a modern way to make asynchronous API calls in JavaScript and is supported by all modern web browsers.

Javascript Memory Allocation and Event Loop


// Code example demonstrating Javascript memory allocation and event loop

// Define function to create new object
function createNewObject() {
  let obj = {};
  obj.prop = 'value';
  return obj;
}

// Define function to create objects in a loop
function createObjectsLoop() {
  let objects = [];

  // Loop ten times to create new objects
  for (let i = 0; i < 10; i++) {
    let newObj = createNewObject();
    objects.push(newObj);
  }

  // Return the created objects
  return objects;
}

// Call the createObjectsLoop function and store the returned objects
let myObjects = createObjectsLoop();

// Log the objects to the console
console.log(myObjects);

// Define function to filter even numbers
function filterEvenNumbers(numbers) {
  let filteredNumbers = [];

  // Loop through each number in the array
  for (let i = 0; i < numbers.length; i++) {
    let number = numbers[i];

    // Check if number is even
    if (number % 2 === 0) {
      filteredNumbers.push(number);
    }
  }

  // Return the filtered numbers
  return filteredNumbers;
}

// Define an array of numbers
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Call the filterEvenNumbers function with the numbers array and store the returned even numbers
let evenNumbers = filterEvenNumbers(numbers);

// Log the even numbers to the console
console.log(evenNumbers);

This code demonstrates Javascript's memory allocation and event loop functionality. The createObjectsLoop function creates a new object using the 'createNewObject' function, and pushes it into an array. The filterEvenNumbers function filters an array of numbers and returns only the even numbers. Both these functions demonstrate how Javascript handles memory allocation by creating and destroying objects as required. The event loop executes code in a non-blocking way, allowing other functions to execute while waiting for time-consuming operations to complete.

Javascript Error Handling

JavaScript is prone to errors due to its dynamic nature. Therefore, error handling is crucial to ensure that the code runs smoothly even when errors occur. Here are some tips for effective javascript error handling:


try {
  // code block
} catch (error) {
  // handle the error
}

The try-catch statement is a basic error handling technique in JavaScript. It can be used to enclose a block of code that is prone to errors. If any error occurs within the try block, the catch block is executed and the error message is displayed to the user. This helps in debugging the code and identifying the root cause of the error.

Another effective technique for error handling is using the console.log() method. This method logs the error messages to the console, allowing developers to examine them during debugging.

Using descriptive error messages is also important. The error messages should be clear and concise, indicating the exact location of the error and the possible solution for the same.

By implementing effective error handling techniques, developers can ensure that their code runs smoothly, even when errors occur.

ES5 vs ES6: What are the Differences?

ES5 and ES6 (ECMAScript 5 and 6) are both versions of the scripting language JavaScript. The primary difference between these two versions is that ES6 introduces new features and syntax, while ES5 is more widely supported by browsers and legacy systems.

Some of the key features and improvements introduced in ES6 include:

  • Arrow functions for simpler and more concise function syntax
  • Classes for defining objects and constructors
  • Template literals for improved string interpolation and formatting
  • Let and const for block-scoped variable declaration
  • Default function parameters for cleaner function definitions
  • Destructuring for simpler and more efficient variable assignment
  • Spread syntax for more flexible function arguments and array manipulation

While these features are not supported by all browsers and legacy systems, they can improve the readability and maintainability of code, as well as make development faster and more efficient. It is important for developers to understand the differences between ES5 and ES6 and choose the appropriate version for their project and target audience.

// Example of defining a class in ES6
class MyClass {
  constructor(name) {
    this.name = name;
  }
  
  sayHello() {
    console.log(`Hello, ${this.name}!`);
  }
}

const myObj = new MyClass("John");
myObj.sayHello(); // Output: "Hello, John!"

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.