Learn javascript in 20 minutes

Javascript is a very famous programming language among developers. So nowadays, everybody talking about javascript and how they can learn javascript?

Lots of of library like jQuery, react, angular build on javascript and they makes development so easy. Apart from that, it’s support system is very strong.

But to learn javascript we need to understand the core concept of javascript. So here we will discuss the core or vanilla javascript.

Essentially javascript is a client side scripting language but it’s also work on server side. It’s created by Brendan Eich on December 4, 1995. Sometime it’s abbreviated as JS.

Now comes to how to start javascript –

  • Here we are using chrome dev tool, go to setting -> More Tools -> Developer Tools.
  • In Sources tab -> Snippets -> + New Snippets.
  • Write code in code section and click on run button and execute javascript code snippet.

Learn javascript in 20 minutes
Fig.1 – Chrome devtool editor.

Hello world program in javascript

It’s a basic program and it’s a very important problem in javascript it does not only verify all environment settings are perfectly working and as well as you know how to print in javascript.

It’s done by using console.log function. But before going further we need to understand javascript comments; in javascript // used for single line comment /**/ for multiline comments. Let’s see how to use comments and print function –

Hello, word program in javascript


/*
*** Value inside "" is a string value
*/
console.log("Welcome to javascript"); // Welcome to javascript

Now you can see we are using both comment format in the above example. In javascript we have 3 basic value first is string, number and boolean string value always inside “” or ”, number is like 1, 2 or 1.2 and boolean will be like true or false.



// This is string value always inside "" or ''
console.log( "This is string value" ); // This is string value

// This is number value
console.log( 1, 1.2 ); // 1, 1.2

// This is boolean value
console.log( true, false );  // true, false

Using variables


var msg = "Welcome to javascript";
console.log(msg); // Welcome to javascript

String Interpolation

String Interpolation is the way by which we can insert a variable into a string.


var name = "xyz", age = 40;
console.log("Welcome " + name + " You are looking " + age + " years old");
console.log(`Welcome ${name} You are looking ${age} years old`); 
 
// Output => Welcome xyz You are looking 40 years old

Concatenation in javascript

Concat is a way by which we can append two string together.


var name = "Learner", msg = "Welcome: " + name;
console.log(msg); // Welcome: Learner

Dynamically and Weakly typed

Javascript is a dynamically typed so it infers variable types at run time. It means on interpretation it will decide the type of variable. Weakly typed languages allow types to be inferred as another type.


var num = 2, str_num = "2";
console.log("num is " + typeof num); // num is number
console.log("str_num is " + typeof str_num); // str_num is string
console.log(num + str_num); // "22"

Here you can see num, str_num both are different type data but in javascript forcefully it will be done and it will give “22” string type result.

Javascript doesn’t have strict typing

Casting in javascript

Casting is a way by whitch we can change type of variables.


var str = "", str_num = "2", num = 2;

// Cast on boolean value
console.log(Boolean(str)); // false
console.log(Boolean(str_num)); // true

// Cast on number value
console.log(Number(str)); // 0
console.log(Number(str_num), " and ", +str_num); // 2

// Cast on string
console.log(String(str_num), " and ", (str_num + "")); // "2"

Here we can see str and str_num is a string type and we can converting into boolean and number type values and num is a number type and we can converting into string type.

Data type in javascript

In javascript we have three type of data type. Primitive, non-primitive and spacial type. Primitive are string, number and boolean, Non-Primitive are array, object, function and spacial types are null and undefined. So we need to understand type and type detection and as well as a need to understand falsy values in javascript.


var num = 2, str = "string", bol = true, arr = [], obj = {}, sp_null = null, sp_un;

// typeof
console.log("Number:: " + typeof(num));  // Number:: number
console.log("String:: " + typeof(str));  // String:: string
console.log("Boolean:: " + typeof(bol)); // Boolean:: boolean

console.log("Array:: " + typeof(arr)); // Array:: object
console.log("Object:: " + typeof(obj)); // Object:: object

console.log("Null:: " + typeof(sp_null)); // Null:: boolean
console.log("Undefined:: " + typeof(sp_un)); // Undefined:: undefined


// instanceof
console.log("Array:: ", arr instanceof Array); // Array:: true
console.log("Object:: ", obj instanceof Object); // Object:: true

typeof is a keyword by which we can find a type of primitive type variables. But be careful when using a non-primitive and spacial type. You can see an array, object, null type is an object.

instanceof is another keyword that is very helpful to get non-primitive type variable types.

Mutable and immutable

Mutable means “liable or subject to change or alteration” and immutable means after it has been created, it can never change.

In JavaScript, only objects and arrays are mutable, not primitive values.


// Mutable
var arr = [1, 2];
arr.push(3);
console.log(arr); // 1, 2, 3

// Immutable
var str = "Immutable value", oStr = str.slice(2); 
console.log(str, " - " ,oStr); // Immutable value - mutable value 

Operators in javascript

An operator is a symbol that operates on a value or a variable. For example: + or – is an operator to perform addition or subtraction. In javascript we have arithmetic, increment and decrement, assignment, relational, logical and bit wise.


var num_1 = 5, num_2 = 3, num = 10, temp;

// Arithmetic
console.log("Addition", num_1 + num_2); // 8
console.log("Subtraction", num_1 - num_2); // 2
console.log("Multiplication", num_1 * num_2); // 15
console.log("Division", num_1 / num_2); // 1.6666666666666667
console.log("Modulo", num_1 % num_2); // 2

// Increment and decrement
console.log("Increment", ++num_1, num_1++, num_1); // 6 6 7
console.log("Decrement", --num_2, num_2--, num_2); // 2 2 1

// Assignment
temp = num; // assign num value in temp
console.log("+=", temp += num); // 20, temp = temp + num
console.log("-=", temp -= num); // 10, temp = temp - num
console.log("*=", temp *= num); // 100, temp = temp * num
console.log("/=", temp /= num); // 10, temp = temp / num
console.log("%=", temp %= num); // 00, temp = temp % num

// Relational
console.log("> & <", num_1 > num_2, " :: ", num_1 < num_2); // > && < true :: false
console.log(">= & <=", num_1 >= num_2, " :: ", num_1 <= num_2); // >= && <= true :: false
console.log("== & !=", num_1 == num_2, " :: ", num_1 != num_2); // == && != false :: true

// Logical
console.log(" && ", num_1 == num && num_1 == num_2); // && false
console.log(" || ", num_1 == num || num_1 == num_2); // || false
console.log(" ! ", num_1 != num || num_1 != num_2); // ! true

Decision control statements

In decision control statements we have if, if…else, nested if and all these statement represent the direction of code. Like

if


var str = "Welcome";

if ( typeof str == "string" ) console.log("It's a string type"); // It's a string type

if…else


// firstno and secondno are numeric variables which holed only numeric value
var firstno = 2, secondno = 3;

// Now we using a comparison operator

if ( firstno > secondno ) { console.log( firstno + " is greater" ); } 
else { console.log( secondno + "  is greater" ); }

// Output => 3 is greater

Ternary operator


var num = 5, isA = ( num % 2 == 0 ) ? "Even" : "Odd";

console.log(num + " is a " + isA); // 5 is a Odd

if…else Ladder


var firstno = 2, secondno = 2; // We can write multiple variable using comma 

if ( firstno > secondno ) { console.log(firstno + " is greater"); } 
else if ( firstno < secondno ) { console.log(secondno + " is greater"); } 
else { console.log("Both number are equal"); }

// Output =>  Both number are equal

Array in javascript

Javascript have array inbuilt. So it’s a set of values, and can hold more then one value.


var arr  = ["first", "second", "third"];

// Get constructor of arr
console.log(arr.constructor); // Array() { [native code] }

// Get length of arr
console.log(arr.length); // 3 

// get 0 th element
console.log(arr[0]); // first

Object in javascript

Javascript have object in form of key value pair. Object keys can hold different type of values.


var ob  = { lang: "Javascript", "creator": "Brendan Eich" };

// Get constructor of ob
console.log(ob.constructor); // Object() { [native code] }


// Get Object length
console.log(Object.keys(ob)); // 2

// Get Object value
console.log(ob["lang"]); // Javascript

for ( var key in ob ) {
    console.log("key is ", Key, " and value is ", ob[key]);
}

// Key is  lang  and value is  Javascript
// Key is  creator  and value is  Brendan Eich

Loop in javascript

Loop used to iterate over all elements of an array, dom, set, list, dictionary and string. In javascript, we have 3 types native of the loop. for, while and do while loop. Apart from that for…in, forEach, and for…of loop is also available in javascript.



// Basic for loop program

for ( var i = 0, len = 5; i < len; i++ ) {
    console.log(i); // 0, 1, 2, 3, 4
}

// Loop with array

var arr  = ["first", "second", "third"];

// for loop
for ( var i = 0, len = arr.length; i < len; i++ ) {
    console.log(arr[i]); // first, second, third
}

// while loop
var i = 0, len = arr.length;

while ( i < len ) {
    console.log(arr[i++]); // first, second, third
}

// do while loop
var i = 0, len = arr.length;

do {
    console.log(arr[i++]); // first, second, third
} while ( i < len );

Break in javascript

We can prevent iterate all elements using a break keyword or stop on desire condition.



// break with for loop
for ( var i = 0, len = 5; i < len; i++ ) {
    console.log(i); // 0, 1, 2

    if ( i == 2 ) {
        break;
    }
}

var arr  = ["first", "second", "third"];

for ( var i = 0, len = arr.length; i < len; i++ ) {
    console.log(arr[i]);
   
    if (arr[i] == "second") break; // first, second
}

Continue in javascript

Can continue to skip over items.



// continue with for loop
for ( var i = 0, len = 5; i < len; i++ ) {

    if ( i == 2 ) { 
        continue;
    } else {
        console.log(i); // 0, 1, 3, 4
    }
}

var arr  = [1, 2, 3, 4, 5];

for ( var i = 0, len = arr.length; i < len; i++ ) {
    
    if ( arr[i] % 2 == 0 ) continue;
    else {
         console.log(arr[i] + " is odd"); // 1 is odd, 3 is odd, 5 is odd
    }
}

Switch in javascript


var num  = 1;

switch ( num ) {
    case 1:
    console.log("First : ", num);
    break;
    
    case 2:
    console.log("Second : ", num);
    break;

    default:
    console.log("Default");
}

// Outpur => First : 1

Function in javascript

Javascript sometime called first-class functions. We can use function like this manner.


// Define function by declaration
function add( a, b ) {
    return a + b;
}

// Define function by expression
var sub = function( a, b ) {
    return a - b;
};

console.log("Add:", add(30, 25), ", Sub:", sub(30, 25)); // Add: 55, Sub: 5

To read more about javascript function, arguments, arrow function, closure, callback.

IIFE

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that execute immediately it is defined.


var globle = "I am globle";

( function( $ ) {
    var msg = "It's IIFE";
    console.log(msg); // It's IIFE
    console.log($); // I am globle
}( globle ) );

// We can't access msg here

We can’t access IIFE variables outside like in previous example we can’t access msg variable outside IIFE structure.

Class in javascript

Recently ES6 introduced class keyword in javascript. We can use class like this manner.



class Student {

    static greet = "Hi"; // static variable

    constructor( name ) {
        this.name = name;
    }

    getName() {
        return this.name;
    }
}

class BE extends Student {
    constructor(name, clg) {
        super(name); // super 
        this.clg = clg;
    }

    getClg() {
        return this.clg;
    }
}

var stu = new BE("abc", 12);
console.log(`${Student.greet} ${stu.getName()}, I think your age is ${stu.getClg()}`); // Hi abc, I think your age is 12

You can read more about class, inheritance, static.

Mozilla is a most useful resource to learn javascript.

You May Also Like

About the Author: Pankaj Bisht