Java Script - Basics
What is JavaScript?
JavaScript is a programming language that is primarily used to create interactive front-end web applications. It is a client-side language, which means that it runs in the user's web browser and can be used to create dynamic user interfaces, validate forms, and control the behavior of other elements on a web page. JavaScript can also be used on the server-side with technologies such as Node.js.
Comments in JavaScript:
Single Line Comments are given using "//" in JavaScript
// This is a Single Line Comment
Multiline Comments are given using /* */
/* This is a
Multiline Comment*/
Comments help to understand code better. They are used to generate documentation.
DataTypes in JavaScript:
There are total 8 datatypes in JavaScript
Variables in JavaScript:
Variable names can be made up of numbers, letters, and $ or _, but may not contain spaces or start with a number. We by convention use camelCase for naming variables in JavaScript.
Uninitialized Variables:
When JavaScript variables are declared, they have an initial value of undefined. If you do a mathematical operation on an undefined variable your result will be NaN which means "Not a Number". If you concatenate a string with an undefined variable, you will get a string of undefined.
var, let and const
Note : Variables which are declared without let, or const are globally scoped and can be accessed from any part of the program.
Note:It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.
Operators in JavaScript
Note: The remainder operator is sometimes incorrectly referred to as the modulus operator. It is very similar to modulus, but does not work properly with negative numbers.
Strings
String values in JavaScript may be written with single or double quotes, as long as you start and end with the same type of quote. Unlike some other programming languages, single and double quotes work the same in JavaScript.
The reason why you might want to use one type of quote over the other is if you want to use both in a string. This might happen if you want to save a conversation in a string and have the conversation in quotes. Another use for it would be saving an <a> tag with various attributes in quotes, all within a string.
\' ------------------------------------------------ single quote
\" ----------------------------------------------- double quote
\\ ----------------------------------------------- backslash\nnewline
\t ----------------------------------------------- tab
\r ----------------------------------------------- carriage return
\b ---------------------------------------------- word boundary
\f ----------------------------------------------- form feed
Strings can be added directly in JavaScript. eg: "First" + "1" = "First1"
In JavaScript strings are immutable. They can only be reassigned.
Arrays
1.We can store different datatypes in a single array. eg: let example = ["String", 1]
2.Arrays can also be nested. These are called multidimensional arrays.
eg: const teams = [["Bulls", 23], ["White Sox", 45]];
3.We can access data nested inside arrays using array indices.
4.Unlike strings, arrays are mutable and can be changed.
5.Arrays are Not Constants
It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.
const ourArray = [50, 40, 30];
ourArray[0] = 15;
6.We can add elements at the end of the array using .push().
const arr2 = ["Stimpson", "J", "cat"];
arr2.push(["happy", "joy"]);
OutPut >>["Stimpson", "J", "cat", ["happy", "joy"]]
7. .pop() method removes the last element of the array and returns it.
const threeArr = [1, 4, 6];
const oneDown = threeArr.pop();
console.log(oneDown);
console.log(threeArr);
OUTPUT>>
6
[1,4]
8. .shift() removes the first element of the array and returns it.
9. .unshift() works exactly like .push(), but instead of adding the element at the end of the array, .unshift() adds the element at the beginning of the array.
Note: There shouldn't be any spaces between the array name and the square brackets, like array [0]. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
Booleans
Functions
Note: A function can include the return statement but it does not have to. In the case that the function doesn't have a return statement, when you call it, the function processes the inner code but the returned value is undefined.
If - Else:
When a condition for an if statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an else statement, an alternate block of code can be executed.
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
=============================================================
Recommended by LinkedIn
Strict equality (===)
If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.
3 === 3 // true
3 === '3' // false
Inequality (!=)
It means not equal and returns false where equality would return true and vice versa.
1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false
Strict Inequality Operator (!==)
It means "Strictly Not Equal" and returns false where strict equality would return true and vice versa.
3 !== 3 // false
3 !== '3' // true
4 !== 3 // true
Greater Than Operator (>)
It compares the values of two numbers. If the number to the left is greater than the number to the right, it returns true. Otherwise, it returns false.
5 > 3 // true
7 > '3' // true
2 > 3 // false
'1' > 9 // false
Greater Than or Equal To Operator (>=)
If the number to the left is greater than or equal to the number to the right, it returns true. Otherwise, it returns false.
6 >= 6 // true
7 >= '3' // true
2 >= 3 // false
'7' >= 9 // false
Less than operator (<)
The less than operator (<) compares the values of two numbers. If the number to the left is less than the number to the right, it returns true. Otherwise, it returns false.
2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
Less than or Equal to operator (<=)
The less than or equal to operator (<=) compares the values of two numbers. If the number to the left is less than or equal to the number to the right, it returns true. If the number on the left is greater than the number on the right, it returns false.
4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
Logical Operators
Logical and operator (&&)
The logical and operator and (&&) returns true if and only if the operands to the left and right of it both are true.
if (num > 5 && num < 10) {
return "Yes";
}
return "No";
Logical Or Operator (||)
The logical or operator (||) returns true if either of the operands is true. Otherwise, it returns false.
if (num > 10 || num < 5) {
return "No";
}
return "Yes";
typeof
In JavaScript, you can determine the type of a variable or a value with the typeof operator, as follows:
typeof 3 //Number
typeof '3' //String
Java Script Loops
While Loop:
If a condition remains true the while loop runs. Care should be taken to avoid infinite loops:
Example:
const ourArray = [];
let i = 0;
while (i < 5) {
ourArray.push(i);
i++;
}
For Loop:
The most common type of JavaScript loop is called a for loop because it runs for a specific number of times.
For loops are declared with three optional expressions separated by semicolons:
Example:
const ourArray = [];
for (let i = 0; i < 5; i++) {
ourArray.push(i);
}
do...while Loop:
It is called a do...while loop because it will first do one pass of the code inside the loop no matter what, and then continue to run the loop while the specified condition evaluates to true.
Example:
const ourArray = [];
let i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
Switch - Case:
If we have many options to choose from, use a switch statement. A switch statement tests a value and can have many case statements which define various possible values. Statements are executed from the first matched case value until a break is encountered. case values are tested with strict equality (===). The break tells JavaScript to stop executing statements. If the break is omitted, the next statement will be executed.
We can add the default statement which will be executed if no matching case statements are found. default is used at last in the switch-case.
switch (fruit) {
case "apple":
console.log("The fruit is an apple");
break;
case "orange":
console.log("The fruit is an orange");
break;
default:
console.log("No case matched");
break;
}
Java Script Objects
Java Script objects consist of properties. We can also add properties to the Java Script objects.
eg: a myDog object
const myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
We can delete properties from object using delete keyword eg:
delete ourDog.bark;
We can check if the property of an object is there or not using <objectname>.hasOwnProperty()