Learning JavaScript - Basics
Learning Basics of JavaScript
Basics of JavaScript
Setup
-
Install cURL (a tool used for downloading content from the internet in the command-line) with:
sudo apt-get install curl
-
Install nvm, with:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
-
To verify installation, enter:
command -v nvm
…this should return ‘nvm’, if you receive ‘command not found’ or no response at all, close your current terminal, reopen it, and try again. Learn more in the nvm github repo -
Install the latest stable LTS release of Node.js (recommended):
nvm install --lts
-
List what versions of Node are installed:
nvm ls
-
Verify that Node.js is installed and the currently default version with:
node --version
. Then verify that you have npm as well, with:npm --version
(You can also use which node or which npm to see the path used for the default versions).
Hello Javascript
console.log('Hello Javascript');
> Hello Javascript
var someVariable = 'Hello Javascript';
console.log(someVariable);
> Hello Javascript
Variables
Java Script 3 major data types:
- number
- string
- boolean
var fullName = 'ThisIsMyName';
console.log(fullName, typeOf fullName);
> ThisIsMyName string
var amICorrect = true;
console.log(amICorrect, typeOf amICorrect);
> true boolean
var myNumber = 47;
console.log(myNumber, typeOf myNumber);
> 47 number
The variables which are defined using var
are given undefined
as value, until they are assigned a value. This is done in the Memory Creation
phase. Which we will be coming across in the future posts.
var noVar;
console.log(noVar);
>>> undefined
noVar = "I'm not a variable";
console.log(noVar);
>>> I'm not a variable
We can take input from the user, for example in the browser we can use the prompt
function to create a pop-up box, where the user can enter a value.
var takeInput;
takeInput = prompt("Give me some Input");
For printing the varialbes in between string data and which is a multi-line we can use the interpolation. Notice how we are using backtick symbol to denote the start of the string and the backtick symbol again to denote the end of the string. And to have any varialbe we can use ${variable_name}
.
console.log(`
This is a multi-line
string.
Where I can even call
variables. like ${fullName}
and ${myNumber}.
`)
>>>
This is a multi-line
string.
Where I can even call
variables. like ThisIsMyName
and 47.
Operators
We can use +
, -
, *
and /
to perform arithmetic operations.
var listPrice = 799
var salePrice = 199
var discount = ( (listPrice - salePrice)/listPrice ) * 100;
console.log(`${discount}%`);
>>> 75.09386733416771%
The asnwer which has so many decimal points can be made clean by using round
functin from Math
.
displayDiscount = Math.round(discount);
console.log(`${displayDiscount}%`);
>>> 75%
Operator Precedence can be best understand from here
Conditionals
if (' ') console.log('This is True');
>>> This is True
if (1) console.log('This is True');
>>> This is True
if ('FALSE') console.log('This is True');
>>> This is True
if (true) console.log('This is True');
>>> This is True
if (false) console.log('This is NOT going to be Printed');
>>>
if (0) console.log('This is NOT going to be Printed');
>>>
if ('') console.log('This is NOT going to be Printed');
>>>
if (null) console.log('This is NOT going to be Printed');
>>>
if (0) console.log('This is NOT going to be Printed');
>>>
var iAmGoingToBeUndefined;
if (iAmGoingToBeUndefined) console.log('This is NOT going to be Printed');
>>>
var someArray = []; // new Array()
if (someArray) console.log('This is True');
>>> This is True
var someObject = {}; // new Object()
if (someObject) console.log('This is True');
>>> This is True
The if
condition will be evaluated and run the code inside the block if the condition is true. So to run the code of if
block the condition must be Truthy
.
In JavaScript, 0
, false
, ''
, null
, NaN
, undefined
are Falsy
values.
Remaining everything else is Truthy
.
Nested ifs and Logical Operators.
var isEmployee = true;
var isLoggenIn = true;
var isAdmin = true;
if (isEmployee) {
if (isLoggenIn) {
if (isAdmin) {
console.log('Welcome Mr. Adminva');
}
}
}
>>> Welcome Mr. Adminva
The content will be printed only if all
the three are true. But there is a better approach using Logical AND (&&)
operator.
if (isEmployee && isLoggenIn && isAdmin) {
console.log('Welcome Mr. Adminva');
}
else {
console.log('You are not authorized');
}
>>> Welcome Mr. Adminva
Similary if we want to pass the condition if any
of the condition is true, then
we use Logical OR(||)
operator.
var isMom = false;
var isDad = false;
var isSister = true;
if (isMom || isDad || isSister) {
console.log('You are a family member');
}
else {
console.log('Kaun hai miya tum??r');
}
>>> You are a family member
Ternery Operator
The ternery operator ?
whatever is before, if evaluated to true
first expression is executed, otherwise the second expression is executed.
Syntax:
condition ? expression1 : expression2
var authenticated = true;
if (authenticated) {
console.log('Welcome');
}
else {
console.log('Show login Options');
}
>>> Welcome
// Alternate shorted approach
console.log(authenticated ? 'Welcome' : 'Show login Options');
>>> Welcome
Switch and Case
The switch
statement is used to perform different actions based on different conditions.
Given a value, the switch
statement evaluates the value and executes the code block(case
) corresponding to the value.
var userType = 'Analyst';
switch (userType) {
case 'Manager':
console.log('Welcome Manager');
break;
case 'Admin':
console.log('Welcome Admin');
break;
case 'Developer':
console.log('Welcome Developer');
break;
case 'Tester':
console.log('Welcome Tester');
break;
case 'Analyst':
console.log('Welcome Analyst');
break;
default:
console.log('Welcome');
}
>>> Welcome Analyst
If we look carefully, we have a break
after each case, because we want to stop the execution of the code block after the case is executed. If we don’t have the break statement, the code block will be executed for all the cases which are the below the current case.
Type Coercion
console.log("2" + 2);
>>> 22
🤯🤯🤯🤯 Whattttttttt…
Java Scripts does type coercion
which is convert one data type to another automatically when it faces any issue with the statement. Like in above example adding a string
and a number
is not possible, so JS automatically converts the number
to string
and concatenates the two.
var user = 2;
if (user == "2"){
console.log('Condition should be false, but........');
}
>>> Condition should be false, but........
As discussed, here JavaScript does type coercion
and convertes user which is number 2 to string “2”. So the condition is true
.
We can avoid this by using ===
operator.
var user = 2;
if (user === "2"){
console.log('Condition should be false, but........');
}
>>>
END!
That is it for today, getting to know some basics in Java Script. We will see more in the upcoming days.
Note: This material is created as part of learning Java Script from various resource, like Hitesh Choudhary’s JS Course and Akshay Saini’s Namaste JS Course