JavaScript Cheatsheet for Beginners 🔥
Tags: javascript, beginners, cheatsheet, programming
Published: 2021-07-26 11:56:59

---
title: JavaScript Cheatsheet for Beginners 🔥
published: true
description: A simple JavaScript JavaScript cheat sheet for beginner buddies!
tags: JavaScript, Beginners, Cheatsheet, Programming
cover_image: ![cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/37i6w76zeu2b78jfwbbn.png)
 
---
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](https://cdn.hashnode.com/res/hashnode/image/upload/v1627259103367/96GNGCEqv.png)

## Including JavaScript in an HTML Page

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

```js
<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:
```js
<script src="myscript.js"></script>
```

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258264423/KaikIIGDdg.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.

```js
// My name is Mr Unity Buddy 

/*My name
is
Mr Unity Buddy
*/
```
________________________________________________________________________________________

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258295189/mUDthPh2l.png)
JavaScript syntax is the set of rules, how JavaScript programs are constructed:
```js
// 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258314999/nlq_2bWfi.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.

```js
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](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258340618/Hv4tCh2Vy.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:
```js
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:
```js
let x = "16" + "Volvo";
```
> When adding a number and a string, JavaScript will treat the number as a string.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627219786897/X8pfOqg1s.png)
Learn more about Js Data types by @[Bello](@techstack)'s [article](https://techstack.hashnode.dev/javascript-data-types)

### 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 👇

```js
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](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258371859/-62V8AXLd.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, ...)

```js
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: `{}`

```js
// 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](https://faheemkhan97.hashnode.dev/function-in-javascript-a-complete-guide-for-beginners) by @[Faheem Khan](@FaheemKhancodes)

________________________________________________________________________________________
![STRINGS (1).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258948728/SPdP1ZUOD.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1627221203986/bS4m2V6SI.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:
```js
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`:

```js
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](https://sjsouvik.hashnode.dev/js-objects-in-depth) by @[Souvik Jana](@sjsouvik)
________________________________________________________________________________________


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258411657/H2NDymIus.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:
```js
name = "Unity buddy" // or
name = 'Unity Buddy'
```
### String length
To find a string's length, simply use `length` property.
```js
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
text.length;    // Will return 26
```
There are many JavaScript string methods, in [this article] @[Niall Maher](@nialljoemaher) has written 26 built-in string methods.
________________________________________________________________________________________
![booleanspng](https://cdn.hashnode.com/res/hashnode/image/upload/v1627259033207/eX5Gwu2u2.png)
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:
```js
Boolean(10 > 9)        // returns true
```

Very easier,
```js
(10 > 9)              // also returns true
10 > 9                // also returns true
```

_________________________________________________________________________________


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258448283/EKtp7_8tD.png)
JavaScript arrays are used to store multiple values in a single variable.
```js
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:

```js
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.

```js
// Array syntax
const array_name = [item1, item2, ...];     
```
As an example,
```js
const games = ["COD", "Overwatch", "Among Us"];
```
Spaces and line breaks are not important. A declaration can span multiple lines:
```js
const games = [
  "COD",
  "Overwatch",
  "Among Us"
];
```
### Accessing  an Array Element
You access an array element by referring to the **index** number:

```js
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:

```js
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`

```js
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:

```js
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myGames;
```
See some commonly used JS array methods in [this article](https://shreyazz.hashnode.dev/javascript-array-methods) by @[Shreyas Pahune](@shreyazz)
_________________________________________________________________________________

![STRINGS.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627259009668/bwZ2JJNAX.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1627256135616/_47jxnuNI.png)

```js
if (age < 18) text = "Not eligible to vote";
```
### Logical Operators

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627256199160/g-eagkkSG.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](https://cdn.hashnode.com/res/hashnode/image/upload/v1627256467765/Psz3w4XEN.png)
_________________________________________________________________________________

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258483659/5kZsumDv0.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
```js
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`. 

```js
if (age < 18) {
  message = "Too young to vote";
}
```
### `else` Statement
```js
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.

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

```js
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.

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

_________________________________________________________________________________
![STRINGS (2).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258901873/4Avaa1NFJF.png)
The `switch` statement is used to perform different actions based on different conditions.
```js
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,
```js
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 
```html
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:
```js
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:
```js
let x = "0";
switch (x) {
  case 0:
    text = "Off";
    break;
  case 1:
    text = "On";
    break;
  default:
    text = "No value found";
}
```

_________________________________________________________________________________
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627258585247/L9xVOFJJF.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:
```js
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
```js
for (let i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}
```

### The For Loop
The for loop has the following syntax:
```js
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.

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

Result:
```html
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
```

### `while` Loops

```js
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.

```js
while (i < 10) { // While the variable is less than 10
  text += "The number is " + i;
  i++;
}
```
### The Do While Loop
```js
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.

```js
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](@techstack) has a wonderful article - [JavaScript Loops](https://techstack.hashnode.dev/javascript-loops)

JavaScript has number of librararies. React and Node.js are popular. If you want to learn more about them, read these articles 
- [React Cheat Sheet for Beginners](https://lo-victoria.com/react-cheat-sheet-for-beginners) by @[Victoria Lo](@victoria)
- [Node.js cheatsheet](https://giuliachiola.hashnode.dev/nodejs-cheatsheet) by @[Giulia Chiola](@giuliachiola)
_________________________________________________________________________________

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!

[Originally](https://mr-unity-buddy.hashnode.dev/javascript-cheat-sheet-for-beginners) published on Hahshnode