JavaScript - basics

revision:


Content

JavaScript (JS) is a light-weight object-oriented programming language JavaScript can change HTML elements and CSS properties some examples JavaScript.info - examples

JavaScript (JS) is a light-weight object-oriented programming language

top

It is used by several websites for scripting webpages and supported in several operating systems - including, Windows, macOS, etc.
JS provides good control to the users over the web browsers. All popular web browsers support JavaScript, because they provide built-in execution environments.

JavaScript follows the syntax and structure of the C programming language and is therefore a structured programming language. It is foremost an object-oriented programming language that uses prototypes rather than using classes for inheritance. It is a case-sensitive language.

Where to put JavaScript?

In HTML, JavaScript code is inserted between "script" and "/script" tags; scripts can be placed in the "body", or in the "head" section of an HTML page, or in both.

Scripts can also be placed in external files. JavaScript files have the file extension ".js". To use an external script, put the name of the script file in the "src (source)" attribute of a "script" tag.

By including JavaScript in an HTML page, an external JS file can be called.

Placing scripts at the bottom of the "body" element improves the display speed, because script interpretation slows down the display.

JavaScript specificities:

1/ Code structure: statements are delimited with a semicolon; a line-break is also treated as a delimiter.

2/ Semicolons are not required after code blocks {...} and syntax constructs with them, like loops.

3/ Strict mode: to fully enable all features of modern JavaScript, we should start scripts with "use strict".

4/ The "use strict" directive must be at the top of a script or at the beginning of a function body.

5/ Variables can be declared using "let", "const" (constant, can't be changed), "var" (old-style).

6/ A variable name can include letters and digits, but the first character may not be a digit.

7/ Characters $ and _ (i.e. underscore) are normal, on par with letters.

8/ Non-Latin alphabets and hieroglyphs are also allowed, but commonly not used.

9/ There are 7 data types:

a/ 'number' for both floating-point and integer numbers,

b/ 'string' for strings,

c/ 'boolean' for logical values: true/false,

d/ 'null' – a type with a single value null, meaning “empty” or “does not exist”,

e/ 'undefined' – a type with a single value undefined, meaning “not assigned”,

f/ 'object' and 'Symbol' – for complex data structures and unique identifiers.

P.S. The typeOf operator returns the type for a value, with two exceptions: null and function.

10/ Operators:

a/ arithmetical: regular: * + - /, also % for the remainder and ** for the power of a number. The binary plus "+" concatenates strings. And if any of the operands is a string, the other one is converted to string too.

b/ assignments: there is a simple assignment: a = b and combined ones like a *= 2.

c/ bitwise: bitwise operators work with 32-bit integers at the lowest bit-level.

d/ conditional: the only operator with three parameters: cond ? resultA : resultB. If cond is truthy, returns resultA, otherwise resultB.

e/ logical operators: logical AND (&&) and OR (||) perform short-circuit evaluation and then return the value where it stopped (not necessary true/false). Logical NOT (!) converts the operand to boolean type and returns the inverse value.

f/ comparisons: equality check == for values of different types converts them to a number (except null and undefined that equal each other and nothing else).
// The strict equality operator === doesn't do the conversion: different types always mean different values for it.
// Values null and undefined are special: they equal == each other and dons't equal anything else.
// Greater/less comparisons compare strings character-by-character, other types are converted to a number.

g/ other operators: there are few others, like a comma operator.

11/ output: JavaScript can "display" data in different ways:

a/ Writing into an HTML element, using innerHTML. To access an HTML element, JavaScript can use the "document.getElementById(id) method". The id attribute defines the HTML element. The innerHTML property defines the HTML content.

b/ Writing into the HTML output using document.write(). For testing purposes, it is convenient to use document.write(). !! Using document.write() after an HTML document is loaded, will delete all existing HTML. !!

c/ Writing into an alert box, using window.alert().

d/ Writing into the browser console using console.log(). For debugging purposes, you can call the console.log() method in the browser to display data.

P.S. You can skip the "window" keyword.

JasvaScript allows to interact with the user and includes several user-interface functions.

alert: simply creates an alert box which may or may not have specified content inside it, but it always comes with the "OK" button. It shows a message and pauses the execution of the script until you press the "OK" button. The mini-window that pops-up is called the "modal window".

prompt: this interface function normally contains two arguments: prompt('text', default value); the text is what you want to show the user and the default value argument is optional though it acts like a placeholder inside a text field. It is the most used interface as with it you can ask the user to input something and then use that input to build something.

confirm: the confirm function basically outputs a modal window with a question and two buttons: "OK" and "CANCEL".

The interactions with users happen via popup boxes : alert box, confirm box, and prompt box.

To display line breaks inside a popup box, use a back-slash followed by the character n (\n).

alert box is often used to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. Syntax: window.alert("sometext");. The window.alert() method can be written without the window prefix.

confirm box is often used to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. Syntax: window.confirm("sometext");. The window.confirm() method can be written without the window prefix.

prompt box is often used to allow the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. Syntax: window.prompt("sometext","defaultText");. The window.prompt() method can be written without the window prefix.

Comments can be included in JavaScript:

single line comments - //comment here;

multi-line comments - /* comment here */


JavaScript can change HTML elements and CSS properties

top

JS can change "HTML content" and "HTML attribute values".

examples

code:
                <div>
                    <button type="button" onclick='document.getElementById("dem1").innerHTML = 
                    "Hello JavaScript!"'>Click Me!</button>
                    <a class=dem" id="dem1"></a>    
                </div>
            

Click the button below to change input field to input button.

code:
                <div>
                    <input class="spec" value="OK"></a>
                    <p class="spec">Click the button below to change input field to input button.</p>
                    <button  onclick="myFunction()">Try it</button>
                </div>
                <script>
                    function myFunction() {
                        document.getElementsByTagName("INPUT")[0].setAttribute("type", "button"); 
                    }
                </script>
            

use setAttribute

This is my tagline

code:
                <div class="spec">
                    <h4 style="color:black;" id='heading'>use setAttribute</h4>
                    <p id="vb1">This is my tagline<br><br>
                        <button onclick="modify()"> Click to modify </button>
                    </p>
                </div>
                <script>
                    function modify() {
                        //update style attribute of element "heading"
                        var heading = document.getElementById("heading");
                        heading.setAttribute("style", "color:red");
                    //add style attribute to element "tagLine"
                        var tagLine = document.getElementById("vb1");
                        tagLine.setAttribute("style", "color:blue");
                    }
                </script>
            

play with numbers

Enter first number :-

Enter second number :-

code:
                <div class="spec">
                    <h4 style="color:green">play with numbers</h4>
                    <p>
                        <b>Enter first number :- </b>
                        <input type="number" id="fNum">
                        <br><br>
                        <b>Enter second number :- </b>
                        <input type="number" id="sNum">
                        <br><br>
                        <button onclick="add()">Add</button>
                        <b><p id="result"></p></b>
                    </p>
                </div>
                <script>
                    function add() {
                        //get the values of fNum and sNum using getAttribute()
                        var fNum = Number(document.getElementById("fNum").value);
                        var sNum = Number(document.getElementById("sNum").value);
                        var result = fNum + sNum;
                        //output the result in green colour
                        var output = "Sum of two numbers is " + result;
                        document.getElementById("result").style = "color:green";
                        document.getElementById("result").innerHTML = output;
                        /*note the way we have updated innerHTML and added style attribute of "result" element */
                        
                    }
                </script>
            

JS can change "HTML styles (CSS)".

examples

JavaScript can change the style of an HTML element.
code:
                <div>
                    <p  class="spec"><button type="button" onclick="document.getElementById('dem2').
                    style.fontSize='25px'">Click Me!</button></p>
                    <a class="spec" id="dem2">JavaScript can change the style of an HTML element.</a>
                </div>
            
Hello
code:
                <div class="spec">
                    <div class="vb2">Hello</div>
                    <button class="add">Change CSS style - 1</button>
                </div>
                <style>
                    .vb2{padding: 1vw 2vw; margin-bottom: 0.5vw; font-size: 2vw;}
                    button.add {padding: 0.2vw 1vw;font-size: 0.5vw;}
                </style>
        
                <script>
                    const button = document.querySelector('.add');
                    button.addEventListener('click', () => {
                        const element = document.querySelector('.vb2');
                        element.style.backgroundColor = 'red';
                    });
                </script>
            
Hello
code:
                <div class="spec">
                    <div class="vb3" style="color: red;">Hello</div>
                    <button class="addit">Change CSS style - 2</button>
                </div>
                <style>
                    .vb3{padding: 1vw 2vw; margin-bottom: 0.5vw; font-size: 2vw;}
                    button.addit {padding: 0.2vw 1vw;font-size: 0.5vw;}
        
                </style>
                <script>
                    const button2 = document.querySelector('.addit');
                    button2.addEventListener('click', () => {
                        const element = document.querySelector('.vb3');
                        element.style.color = 'green';
                    });
                </script>
            
Hello
code:
                <div class="spec">
                    <div class="vb4" style="color: red;">Hello</div>
                    <button class="add_more">Change CSS style - 3</button>
                </div>
                <style>
                    .vb4{padding: 1vw 2vw; margin-bottom: 0.5vw; font-size: 2vw;}
                    button.add_more {padding: 0.2vw 1vw;font-size: 0.5vw;}
                    .element{color: blue;}
                </style>
                <script>
                    const button3 = document.querySelector(".add_more");
                    button3.addEventListener("click", changeMultipleCSS);
                    function changeMultipleCSS(e) {
                        // Defining all our CSS styles
                        const myStyles = `
                            display: block;
                            width: 80%;
                            background-color: red;
                            border: 0.2vw;
                            font-size: 3vw;
                            color: white;
                            margin: 2vw;
                            padding-left: 1vw;
                            padding-bottom: 1vw;
                            border: 0.2vw solid blue;
                        `;
                    const element = document.querySelector(".vb4");
                    element.style.cssText = myStyles;
                }
                </script>
            

JS can "hide/show HTML elements".

examples

JavaScript can hide HTML elements.
code:
                <div>
                    <p class="spec"><button type="button" onclick="document.getElementById('dem3').
                    style.display='none'">Click Me!</button></p>
                    <a class="spec" id="dem3">JavaScript can hide HTML elements.</a>
                </div>
            

code:
                <div>
                    <p class="spec"><button type="button" onclick="document.getElementById('dem4').
                    style.display='block'">Click Me!</button></p>
                    <a class="spec" id="dem4" style="display:none">Hello JavaScript!</a>
                </div>
            

Click the "try it" button to toggle between hiding and showing the DIV element:

my DIV element.
code:
                <div class="spec">
                    <p>Click the "try it" button to toggle between hiding and showing the DIV element:</p>
                    <button oclass="more" onclick="hideShow()">try it</button>
                    <div id="vb5">my DIV element.</div>
                </div>
                <style>
                    #vb5 { width: 100%; padding: 5vw 0; text-align: center; background-color: lightblue; margin-top: 2vw;}
                </style>
                <script>
                    function hideShow() {
                        var element = document.getElementById("vb5");
                        if (element.style.display === "none") {
                            element.style.display = "block";
                        } else {
                            element.style.display = "none";
                        }
                    }
                </script>
            

some examples

top

Template strings

examples

code:
                Code: "const title = '"Best reads of 2019"';
                const author = 'Mario';
                const likes = 30;
                let result = 'The blog called ' + title + ' by ' + author + ' has ' + likes + ' likes';
                document.getElementById('id1').innerHTML = result;
                let result1 = `The blog called ${title} by ${author} has ${likes} likes`;
                document.getElementById('id2').innerHTML = result1;"
            

Creating html template

examples

code:
                let html =`
                <h3>${title}</h3>
                <p>By ${author}</p>
                    <span>This blog has ${likes} likes</span>
                `;
                document.getElementById('id3').innerHTML = html;
            
examples

global vs. local scope

code:
                const age1 = 30;
                if(true){
                    const age1 = 40;
                    const name = 'shaun'
                    console.log('inside first code block:', age1, name);
                    if(true){
                        const age1 = 50;
                        console.log('inside second code block:', age1);
                        var test ='hello'
                    }
                }
                console.log('outside code block:', age1, name, test);
            

create input form

examples

Player 1: Ernest

code:
                const para = document.querySelector('#one');
                para.addEventListener('click', updateName);
                function updateName() {
                let name = prompt('Enter a new name');
                para.textContent = 'Player 1: ' + name;
                }  
            

create a heading

examples
code:
                const myHeading = document.querySelector('#two');
                myHeading.textContent = 'Hello world!';
            

JavaScript.info - examples

top
examples
script tag:
               
                <script>
                    alert( 'Hello, world!' );
                </script>
            
script tag:
                <script src="/path/to/script.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/..../lodash.js"></script>
                
                <script src="/js/script1.js"></script>
                <script src="/js/script2.js"></script>

                <script src="file.js"></script>
                <script>
                  alert(1);
                </script>
            
code structure:
                alert('Hello'); alert('World');

                alert('Hello');
                alert('World');

                alert('Hello')
                alert('World')

                alert("Hello");
                [1, 2].forEach(alert);
            
comments:
                // This comment occupies a line of its own
                alert('Hello');
                
                alert('World'); // This comment follows the statement

                /* An example with two messages.
                This is a multiline comment.
                */
                alert('Hello');
                alert('World');
            
"use strict":
                "use strict";
                // this code works the modern way
                ...

                alert("some code");
                // "use strict" below is ignored--it must be at the top
                "use strict";
                // strict mode is not activated

                (function() {
                    'use strict';
                  
                    // ...your code here...
                  })()
            
interaction:
                alert("Hello");

                result = prompt(title, [default]);

                let age = prompt('How old are you?', 100);
                alert(`You are ${age} years old!`); // You are 100 years old!

                result = confirm(question);

                let isBoss = confirm("Are you the boss?");
                alert( isBoss ); // true if OK is pressed