JavaScript Cheat Sheet for Beginners

Β·

13 min read

JavaScript Cheat Sheet for Beginners

Hello, buddies! JavaScript is the world's most popular programming language and it is the programming language of the Web. JavaScript is easy to learn even though some say it is Hard. I have mentioned earlier any programming language can be hard if you didn't give it a try😜!

And about this, this is not a complete tutorial about JavaScript but we can get the basic knowledge about JavaScript and also this can be used as a reference list of JavaScript variables, strings, and other attributes. 🀟


STRINGS (4).png

Including JavaScript in an HTML Page

To include JavaScript inside a page, you need to wrap it properly in <script> tags🎁:

<script type="text/javascript">

//JS code goes here

</script>

With this input, the browser can identify and execute the code properly.

Call an External JavaScript File

You can also place JavaScript in its own file and name it inside your HTML. That way, you can keep different types of code separate from one another, making for better-organized files. If your code is in a file called myscript.js, you would call it:

<script src="myscript.js"></script>

image.png Make sure you use comments only in complex situations. Anway, if you are using comments,

  • Use // for single line comments and,

  • /* */ for multi-line comments.

// My name is Mr Unity Buddy 

/*My name
is
Mr Unity Buddy
*/

image.png JavaScript syntax is the set of rules, how JavaScript programs are constructed:

// How to create variables:
var x;
let y;

// How to use variables:
x = 5;
y = 6;
let z = x + y;

Here are another few points to note,

  • JavaScript is Case Sensitive. unitybuddy and unityBuddy are 2 different variables.
  • You can't use hyphens(-)in JavaScript.
  • Every Js line should be ended with a semicolon ;

image.png Variables are stand-in values that you can use to perform operations. You should be familiar with them from math class.

var, const, let

You have three different possibilities for declaring a variable in JavaScript, each with its own specialties:

  • var β€” The most common variable. It can be reassigned but only accessed within a function. Variables defined with var move to the top when the code is executed.
  • const β€” Can not be reassigned and not accessible before they appear within the code.
  • let β€” Similar to const, the let variable can be reassigned but not re-declared.
var x = 5; //Store value of 5
let x = 10; // Store value of 10
const PI = 3.14159265359; // Store this value of 3.14159265359;

image.png In programming, data types is an important concept. To be able to operate on variables, it is important to know something about the type. Without data types, a computer cannot safely solve this:

let x = 16 + "Volvo";

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result?

JavaScript will treat the example above as:

let x = "16" + "Volvo";

When adding a number and a string, JavaScript will treat the number as a string.

image.png Learn more about Js Data types by Bello's article

JavaScript Types are Dynamic

JavaScript has dynamic types. This means that the same variable can be used to hold different data types, just like below πŸ‘‡

let x;           // Now x is undefined
x = 5;           // Now x is a Number
x = "John";      // Now x is a String
____________________________________
x = "Cat" // Now x is a Cat 😹

image.png A JavaScript function is defined with 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, ...)

function name(parameter1, parameter2, parameter3) {
  // code to 
}
  • Function parameters are listed inside the parentheses () in the function definition.

  • Function arguments are the values received by the function when it is invoked.

  • Inside the function, the arguments (the parameters) behave as local variables.

  • The code to be executed, by the function, is placed inside curly brackets: {}

// Sample Code
function getDaysBetweenTwoDates(start, end) {
    const startDate = new Date(start);
    const endDate = new Date(end);

    const diff = endDate - startDate;

    return Math.ceil(diff / (1000 * 60 * 60 * 24));
}

These are only the basics of JavaScipt function so, you can read Function in JavaScript: A complete guide for beginners by Faheem Khan


STRINGS (1).png

Objects, Properties, and Methods in Real-life

Concept of objects might be somewhat hard so let's take a simple example.

In real life, a flight is an object.

properties of a flight are color and weight, and the methods are pitch(up and down), roll etc.

Games (1).png All flights have the same properties, but the property values differ from flight to flight.

All flight have the same methods, but the methods are performed at different times.

This is the concept of an Object! It's super easy πŸ™Œ

Objects in JavaScript

We have already learned that JavaScript variables are containers for data values.

This code assigns a simple value (F12) to a variable named car:

let flight = "F12";

Objects are variables too. But objects can contain many values.

This code assigns many values (F12, 41 200, White) to a variable named flight:

const car = {name:"F12", weight:"41 200", color:"white"};

The values are written as name: value pairs (name and value separated by a colon).

It is a common practice to declare objects with the const keyword.

This is is the basic concept of an Object in JavaScript. To learn more, you can refer JS Objects in depth by Souvik Jana


image.png

A string (or a text string) is a series of characters just like "Unity Buddy".

Strings are written with quotes. You can use single or double quotes:

name = "Unity buddy" // or
name = 'Unity Buddy'

String length

To find a string's length, simply use length property.

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
text.length;    // Will return 26

There are many JavaScript string methods, in [this article] Niall Maher has written 26 built-in string methods.


booleanspng Very often, in programming, you will need a data type that can only have one of two values, like

  • YES / NO
  • ON / OFF
  • TRUE / FALSE For this, JavaScript has a Boolean data type. It can only take the values true or false.

Boolean() Function

You can use the Boolean() function to find out if an expression (or a variable) is true:

Boolean(10 > 9)        // returns true

Very easier,

(10 > 9)              // also returns true
10 > 9                // also returns true

image.png JavaScript arrays are used to store multiple values in a single variable.

const authors = ["Victoria", "Chris", "Catalin"];

Simply, An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of authors names, for example), storing some authors in single variables could look like this:

let author1 = "Didi";
let author2 = "Uncle Bigaby";
let author3 = "Favourite Jome";

However, what if you want to loop through the authors and find a specific one? And what if you had not 3 authors, but 100?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Using an array literal is the easiest way to create a JavaScript Array.

// Array syntax
const array_name = [item1, item2, ...];

As an example,

const games = ["COD", "Overwatch", "Among Us"];

Spaces and line breaks are not important. A declaration can span multiple lines:

const games = [
  "COD",
  "Overwatch",
  "Among Us"
];

Accessing an Array Element

You access an array element by referring to the index number:

const games = ["COD", "Overwatch", "Among Us"];
let x = games[0];    // x = "COD"

Note πŸ“: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Adding Array Elements

To add a new element, we should give a push

The easiest way to add a new element to an array is using the push() method:

const games = ["COD", "Overwatch", "Cyberpunk"];
fruits.push("Hill Climb Racing");  // Adds a new element (Hill Climb Racing) to fruits

### Changing an Array Element
Following code changes the first element of ```games
cars[0] = "Cyberpunk"; // Change COD into Cyberpunk

Super simple.

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myGames;

See some commonly used JS array methods in this article by Shreyas Pahune


STRINGS.png Comparison and Logical operators are used to test for true or false.

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables or values.

image.png

if (age < 18) text = "Not eligible to vote";

Logical Operators

image.png

Comparing Different Types

Comparing data of different types may give unexpected results.

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. An empty string converts to 0. A non-numeric string converts to NaN which is always false.

Below table shows the result we get when comparing different data types

image.png


Thanks for reading so far and let's play a simple game for 2 mins πŸ˜…


image.png

Very often when we write code, we want to perform different actions for different decisions.

We can use conditional statements in our code to do this.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

if Statement

if (condition) {
  //  block of code to be executed if the condition is true
}

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

if (age < 18) {
  message = "Too young to vote";
}

else Statement

if (condition) {
  //  block of code to be executed if the condition is true
} else {
  //  block of code to be executed if the condition is false
}

Use the else statement to specify a block of code to be executed if the condition is false.

if (age < 18) {
  message = "Too young to vote";
} else {
  message = "Old enough to vote";
}

else if Statement

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 else if statement to specify a new condition if the first condition is false.

if (time < 10) {
  wish = "Good morning";
} else if (time < 20) {
  wish = "Good day";
} else {
  wish = "Good evening";
}

STRINGS (2).png The switch statement is used to perform different actions based on different conditions.

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

This is how it works:

  • 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's see an example,

switch (new Date().getDay()) { // The getDay() method returns 
the weekday as a number between 0 and 6.
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
     day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
}

So, our result is going to be

Sunday

The break Keyword

When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution inside the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.

πŸ“ If you omit the break statement, the next case will be executed even if the evaluation does not match the case.

The default Keyword

The default keyword specifies the code to run if there is no case match:

switch (new Date().getDay()) {
  case 6:
    text = "Today is Saturday";
    break;
  case 0:
    text = "Today is Sunday";
    break;
  default:
    text = "Looking forward to the Weekend";
\\ Result is 'looking forward to the weekend'
}

Strict Comparison

Switch cases use strict comparison (===).

The values must be of the same type to match.

A strict comparison can only be true if the operands are of the same type.

In this example there will be no match for x:

let x = "0";
switch (x) {
  case 0:
    text = "Off";
    break;
  case 1:
    text = "On";
    break;
  default:
    text = "No value found";
}

image.png Last part! You are awesome πŸ‘πŸ‘

Loops are cool, if you want to run the same code over and over again, each time with a different value.

Often this is the case when working with arrays:

text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<be>";

Instead of this, you can just use a loop

for (let i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}

The For Loop

The for loop has the following syntax:

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}
  • Statement 1 is executed (one time) before the execution of the code block.

  • Statement 2 defines the condition for executing the code block.

  • Statement 3 is executed (every time) after the code block has been executed.

for (let i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}

Result:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4

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. It means the value is changing and while the condition is true, while loops work.

while (i < 10) { // While the variable is less than 10
  text += "The number is " + i;
  i++;
}

The Do While Loop

do {
  // code block to be executed
}
while (condition);

The do...while loop is a variant of the while loop. 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.

do {
  text += "The number is " + i;
  i++;
}
while (i < 10);

Cool, it is super easy and clear. If you want learn more about Js loops, Bello has a wonderful article - JavaScript Loops

JavaScript has number of librararies. React and Node.js are popular. If you want to learn more about them, read these articles


Woah, that's it! πŸ’™πŸ’™ This is not a full tutorial but I hope beginner buddies can get a basic concept about functions, loops, operators etc. here. Thanks for reading this long article and Happy Coding!

Β