JavaScript

JavaScript?

  • JavaScript is the Programming Language for the Web
  • JavaScript can update and change both HTML and CSS
  • JavaScript can calculate, manipulate and validate data

Syntax :

var x, y;          // How to declare variables
x = 5; y = 6;      // How to assign values
z = x + y;         // How to compute values 

Strings are text, written within double or single quotes:

"John Doe"

'John Doe' 

JavaScript Variables

  • In a programming language, variables are used to store data values.
  • JavaScript uses the var keyword to declare variables.
  • An equal sign is used to assign values to variables
var x;

x = 6; // x is assigned the value of 6

Comparison Operators

  • The ‘==’ operator tests for abstract equality i.e. it does the necessary type conversions before doing the equality comparison.
  • But the ‘===’ operator tests for strict equality i.e it will not do the type conversion hence if the two values are not of the same type, when compared, it will return false.

Example

<script> 
    // In R.H.S. string "3" is converted into 
    // number 3, hence returns true. 
    document.write(9 == "9");  
      
    // used for next line 
    document.write('<br>') 
   
    // Here no type conversion takes place, 
    // hence returns false 
    document.write(9 === "9");  
</script> 

Output:
true
false

Exercise

Write a simple JavaScript program that on button click displays the current timestamp on screen.

<!DOCTYPE html>
<html>
<body>

<h2>My First JavaScript</h2>

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()"> // using the Date() function
Click me to display Date and Time.</button>

<p id="demo"></p> // Using the id attribute

</body>
</html>