× Home

JavaScript

Comments

                  
                  
                   var number = 5; // in-line comment
                   /*
                       Multi-line comment 1
                       Multi-line comment 2
                       Multi-line comment 3
                   */
                  
              

Data Types and Variables

Variable

  • A variable allows computer to store and manipulate data in a dynamic fashion.
  • It is basically a label to point to a data.
  • There are three ways to declare a variable in JS.
    1. var myName = "abc"
    2. let ourname = "xyz"
    3. const pi = 3.14
  • "var" can be used throughout in our whole program.
  • "let" will only be used with in the scope of where you declared that.
  • "const" is variable that can never change.

Storing values with assignment operator

                   
                   
                    // try to use semi-colon
                    var a; // here we are declaring a variable 
                    var b = 2; // here we are declaring and assinging in one line
                     // equal (=) sign is an assinging operator
                   
               

Initializing variable with assignment operator

                   
                   
                    // Initialize these three variables 
                    var a = 5;
                    var b = 10;
                    var c = "I am a";

                    // updating above variables 
                    a = a + 1; // 6
                    b = b + 5; // 15
                    c = c + " String!"; // "I am a String!"
                   
               

Case Senstivity in Variables

                   
                   
                    // Declarations
                    var StUdLyCapVaR;
                    var properCamelCase;
                    var TitleCaseOver;

                    // Assignments
                    STUDLYCAPVAR = 10;
                    PRoperCAmelCAse = "A String";
                    tITLEcASEoVER = 9000;

                    // this will give error
                   
               

In above code the declared variable are not same as variable used during assignment.

                    
                    
                     // Declarations with camel case
                     var studlyCapVar;
                     var properCamelCase;
                     var TitleCaseOver;
 
                     // Assignments
                     studlyCapVar = 10;
                     properCamelCase = "A String";
                     TitleCaseOver = 9000;
                    
                

Basic Maths

Adding Numbers

                       
                       
                        var sum = 10 + 0; // 10
                       
                   

Subtracting Numbers

                       
                       
                        var difference = 45 - 3 // 42
                       
                   

Multiplying Numbers

                       
                       
                        var product = 8 * 10; // 80
                       
                   

Dividing Numbers

                       
                       
                        var quotient = 66 / 33; // 2
                       
                   

Incrementing Numbers

                       
                       
                        var myVar = 87;

                        myVar = myVar + 1;
                        myVar++; // shortcut
                       
                   

Decrementing Numbers

                       
                       
                        var myVar = 11;

                        myVar = myVar - 1;
                        myVar--;
                       
                   

Decimal Numbers

  • A.K.A floating point numbers
                       
                       
                        var ourDecimal = 5.7;
                       
                   

Multiply Decimals

                       
                       
                        var product = 2.0 * 2.5;
                       
                   

Divide Decimals

                       
                       
                        var quotient = 4.4 / 2.0;
                       
                   

Finding a remainder

                       
                       
                        var remainder = 11 % 3; 
                       
                   

Compound Assigment with Augmented Addition

                       
                       
                        var a = 3;
                        var b = 17;
                        var c = 12;

                        a += 12; // same as a = a + 12
                        b += 9;
                        c += 7;
                       
                   

Compound Assigment with Augmented Subtraction

                       
                       
                        var a = 11;
                        var b = 9;
                        var c = 3;

                        a -= 6;
                        b -= 15;
                        c -= 1;
                       
                   

Compound Assigment with Augmented Multiplication

                       
                       
                        var a = 5;
                        var b = 12;
                        var c = 4.6;

                        a *= 5;
                        b *= 3;
                        c *= 10;
                       
                   

Compound Assigment with Augmented Division

                       
                       
                        var a = 48;
                        var b = 108;
                        var c = 33;

                        a /= 12;
                        b /= 4;
                        c /= 11;
                       
                   
Strings

Declare String Variables

  • Anything value surrounded by double, single quotation mark or back tick is a string.
                    
                    
                     var firstName = "Alan";
                     var lastName = 'Turing';
                    
                

Escaping Literal Quotes in String

                   
                   
                    // var myStr = "I am a "double quoted" string inside "double quotes"";

                    // by using "\" we can escape quotes 

                    var myStr = "I am a \"double quoted\" string inside \"double quotes\"";
                
               

Quoting Strings with Single Quotes

  • We can accomplish things without escaping quotes using single quote.
                   
                   
                    // var myStr = "<a href=\"http://www.example.com\" target =\"_blank\">Link<a/>";
                    // use single quote in beginning and in ending.
                    var myStr = '<a href="http://www.example.com" target ="_blank">Link<a/>';
                   
               

Using back ticks to use single and double quote inside a string.

                   
                   
                    var myStr = `'<a href="http://www.example.com" target ="_blank">Link<a/>'`;
                   
               

Escape Sequences in Strings

  • There are other things that we can escape out from.
                   
                   
                    CODE    OUTPUT 
                    \'      single quote 
                    \"      double quote 
                    \\      backslash
                    \n      newline
                    \r      carriage return
                    \t      tab 
                    \b      backspace 
                    \f      form feed 
                   
               

Concatenating Strings with Plus Operator

                   
                   
                    var ourStr = "I come first. " + "I come second.";
                   
               

Concatenating Strings with Plus Equals Operator

                   
                   
                    var ourStr = "I come first. ";
                    ourStr += "I come second."
                    console.log(ourStr); // "I come first. I come second."
                   
               

Constructing Strings with Variables

                   
                   
                    var ourName = "freeCodeCamp";
                    var ourStr = "Hello, our name is " + ourName + ", how are you?";
                    console.log(ourStr); // "Hello, our name is freeCodeCamp , how are you?"
                   
               

Appending Variables to Strings

                   
                   
                    var anAdjective = "awesome!";
                    var ourStr = "freeCodeCamp is ";
                    ourStr += anAdjective; 
                    console.log(ourStr); // "freeCodeCamp is awesome!"
                   
               

Find Length of String

  • We use .length property to find the length of string.
                    
                    
                     var firstNameLength = 0;
                     var firstName = "Ada";

                     firstNameLength = firstName.length;
                     console.log(firstNameLength); // 3
                    
                

Bracket Notation to Find First Character in String

                   
                   
                    var firstLetterOfFirstName = "";
                    var firstName = "Ada";

                    firstLetterOfFirstName = firstName[0]; // 0 base index
                   
               

String Immutability

  • Strings are immutable, meaing that it cannot be altered once created. This doesn't mean that they cannot be changed, just that the individual characters of string literal cannot be changed.
                   
                   
                    var myStr = "Jello World";

                    // myStr[0] = "H"; this throws an error because of the immutability of strings.
                    // we can change the whole content of the string variable.
                    myStr = "Hello World";
                   
               

Bracket Notation to Find Nth Character in String

                   
                   
                    // not only first character we can access character at 2nd and 3rd position.
                    var firstName = "Ada";
                    var secondLetterOfFirstName = firstName[1];
                    var thirdLetterOfFirstName = firstName[2];
                   
               

Bracket Notation to Find Last Character in String

                   
                   
                    var name = "Harry";
                    var lastCharacter = name[name.length-1];
                   
               

Bracket Notation to Find Nth-to-Last Character in String

  • We just have to subtract the number from ".length".
                    
                    
                     var name = "Ada";
                     var thirdToLastLetterOfName = name[name.length-3];
                    
                

Word Blanks

  • Using our knowledge of strings we have to build a word game.
                   
                   
                    function wordBlanks(myNoun, myAdjective, myVerb, myAdverd){
                        // your code below this line 
                        var result = "";
                        result += "The " + myAdjective + " " + myNoun + " " + myVerb + " to the store " + myAdverb;
                        // your code above this line 
                        
                        return result;
                    }

                    console.log(wordBlanks("dog", "big", "ran", "quickly"));
                   
               

Store Multiple Values with Arrays

example ↓

                   
                   
                    var ourArray = ["John", 23];
                   
               

Nested Arrays

  • When one of the element in an array is another array that's called the nested array.
                       
                       
                        var ourArray = [["the universe", 42], ["everything", 101010]];
                       
                   

Access Array Data with Indexes

                       
                       
                        var ourArray = [50, 60, 70];
                        var ourData = ourArray[0] // equals 50
                       
                   

Modify Array Data with Indexes

                       
                       
                        var ourArray = [18, 64, 99];
                        ourArray[1] = 45; // ourArray now equals [18, 45, 99].
                       
                   
  • Earlier we were not able to modify string using bracket notations.

Access Multi-dimensional Array with Indexs

  • We use double bracket to select element in multi-dimensional array.
                       
                       
                        var myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [[10, 11, 12], [13, 14]]];
                       
                   

Manipulate Arrays with push()

  • We can append data to the end of an array with the push function.
                       
                       
                        var ourArray = ["Stimpson", "J", "cat"];
                        ourArray.push(["happy", "joy"]);
                        // ourArray now equals ["Stimpson", "J", "cat", ["happy", "joy"]]
                       
                   

Manipulate Arrays with pop()

  • We can remove final element from an array with pop function.
                       
                       
                        var ourArray = [1, 2, 3];
                        var removedFromOurArray = ourArray.pop();
                        // removedFromOurArray now equals 3, and ourArray now equals [1, 2]
                       
                   

Manipulate Arrays with shift()

  • shift function removes the first element from an array.
                       
                       
                        var ourArray - ["Stimpson", "J", ["cat"]];
                        var removedFromOurArray = ourArray.shift();
                        // removedFromOurArray now equals "Stimpson", and ourArray now equals ["J", ["cat"]]
                       
                   

Manipulate Arrays with unshift()

  • Adds element to the beginning of the array.
                       
                       
                        var ourArray - ["Stimpson", "J", ["cat"]];
                        ourArray.unshift("Happy");
                        // ourArray now equals ["Happy", "J", ["cat"]]
                       
                   

Shopping List

  • Another example of shopping list
                       
                       
                        var myList = [["cereal", 3], ["milk", 2], ["bananas", 3], ["juice", 2], ["eggs", 12]];     
                       
                   

Write Reusable Code with Functions

                   
                   
                    // Funtion setup
                    function ourReusableFunction() {
                        console.log("Heyya, World");
                    }

                    ourReusableFunction(); // function call
                    ourReusableFunction(); 
                   
               

Passing Values to Functions with Arguments

  • Parameters are variables that acts as placeholders for the values that are to be input to a function when it is called.
                       
                       
                        // Example 
                        function ourFunctionWithArgs(a, b){
                            console.log(a - b);
                        }
                        ourFunctionWithArgs(10, 5); // output 5
                       
                   

Global Scope and Functions

  • Scope refers to visibility of variables.
  • Variables which are defined outside the of a function block have global scope. Global scope means it can be seen everywhere in your JS code.
                       
                       
                        // Declare global variable here 
                        var myGlobal = 10;

                        function fun1()
                        {
                            oopsGlobal = 5; // we can also declare variable without using "var" keyword
                            // if we do use "var" keyword it will be scoped to this function but we can't be used outside this function.
                            // but if we remove "var" keyword then the variable will automatically become global and can be accessed anywhere.
                        }

                        function func2()
                        {
                            var output = "";
                            if(typeof myGlobal != "undefined") {
                                output += "myGlobal: " + myGlobal;
                            }
                            if(typeof oopsGlobal != "undefined") {
                                output += " oopsGlobal: " + oopsGlobal;
                            }
                            console.log(output);
                        }
                        func1();
                        func2();
                       
                   

Local Scope and Functions

  • Variable which are declared within a function and function parameter have local scope, that means they are only visible with in the function.
                       
                       
                        function myLocalScope() {
                            var myVar = 5;
                            console.log(myVar);
                        }
                        myLocalScope();

                        console.log(myVar); // this gives error
                       
                   

Global vs. Local Scope in Functions

  • It is possible to have local and global variable with the same name.
  • When you do this local varaible takes precedence over the global variable.
                        
                        
                         var outerWear = "T-shirt"; // global variable

                         function myOutfit() {
                            var outWear = "sweater"; // local variable
                            retrun outerWear;
                         }

                         console.log(myOutfit()); // output: "sweater "
                         console.log(outerWear); // output: "T-shirt "
                        
                    

Return a value from a Function with Return

  • You can return a value from a function with this return statement.
                       
                       
                        function minusSeven(num) {
                            return num - 7;
                        }

                        console.log(minusSeven(10)); // output: 3
                       
                   

Understanding Undefined Value Returned from a Function

  • If we don't specify a return value then it is "undefined".
                       
                       
                        // Example
                        var sum = 0;
                        function addThree() {
                            sum = sum + 3;
                        }

                        function addFive() {
                            sum += 5; 
                        }
                        console.log(addFive()); // undefined
                       
                   

Assignment with a Returned Value

  • We can assign return value from a function to a variable.
                       
                       
                        var changed = 0;

                        function change(num) {
                            return (num + 5) / 3;
                        }

                        changed = change(50);
                       
                   

QUEUE - Stand in Line

                   
                   
                    function nextInLine(arr, item) {
                        arr.push(item);
                        return arr.shift();
                    }

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

                    console.log("Before: " + JSON.stringify(testArr));
                    console.log(nextInLine(testArr, 6));
                    console.log("After: " + JSON.stringify(testArr));
                   
               

Boolean Values

  • Booleans are another data types in JS. There are only two values true or false.
                       
                       
                        function welcomeToBooleans() {
                            return true; 
                        }
                       
                   

Use Conditional Logic with If Statements

  • If statements is used to make decisions in code. The keyword "if" tells JS to execute the code in curly braces under certain conditions defined in the parenthesis.
                       
                       
                        function ourTrueOrFalse(isItTrue) {
                            if(isItTrue) {
                                return "Yes, it's true";
                            }
                            return "No, it's false";
                        }
                       
                   

Comparision with the Equality Operator

  • Gives true or false if the comparision is correct or incorrect respectively.
  • ==
                       
                       
                        function testEqual(val) {
                            if (val == 12) {
                                return "Equal";
                            }
                            return "Not Equal";
                        }

                        testEqual(10); // returns "Not Equal"
                       
                   

Comparision with the Strict Equality Operator

  • The equality operator (==) converts both the value to common type while the strict equality operator (===) does not do the type conversion.
                           
                           
                            3 === 3 // true 
                            3 === '3' // false
                           
                       
                           
                           
                            function testStrict(val) {
                                if(val === 7) {
                                    return "Equal";
                                }
                                return "Not Equal";
                            }

                            testStrict(10); // returns "Not Equal"
                           
                       

Practice Comparing Different Values

                           
                           
                            function compareEquality(a, b) {
                                if (a == b) {
                                    return "Equal";
                                }
                                return "Not Equal";
                            }
                            console.log(compareEquality(10, "10")); // logs "Not Equal"
                           
                       
                           
                           
                            function compareEquality(a, b) {
                                if (a === b) {
                                    return "Equal";
                                }
                                return "Not Equal";
                            }
                            console.log(compareEquality(10, 10)); // logs "Equal"
                           
                       

Comparison with the Inequality Operator

  • Checks if two values are not equal, if they are not equal then it becomes true.
                           
                           
                            function testNotEqual(val) {
                                if (val != 99) {
                                    return "Not Equal";
                                }
                                return "Equal";
                            }

                            console.log(testNotEqual(10)); // prints "Not Equal"
                           
                       

Comparison with the Strict Inequality Operator

                           
                           
                            function testStrictNotEqual(val) {
                                if(val !== 17) {
                                    return "Not Equal";
                                }
                                return "Equal";
                            }

                            console.log(testStrictNotEqual(10)); // prints "Not Equal"
                           
                       

Comparisons with the Greater Than Operator

                           
                           
                            function testGreaterThan(val) {
                                if (val > 100) {
                                    return "Over 100";
                                }

                                if (val > 10) {
                                    return "Over 10";
                                }

                                return "10 or Under";
                            }

                            console.log(testGreaterThan(10)); // prints "10 or Under"
                           
                       

Comparision with the Greater Than OR Equal To Operator

function testGreaterOrEqual(val) { if (val >= 20) { return "20 or Over"; } if (val >= 10) { return "10 or Over"; } return "Less than 10"; } console.log(testGreaterOrEqual(10)); // prints "10 or Over"
1:18:06