What is JavaScript?

Getting JavaScript onto your webpage.
  1. Write it right on the HTML page.
    1. <script>
    2. // All JavaScript Code goes here
    3. </script>
  2. Import the JavaScript file:
    1. <script src="sampleJavaScript.js" type="text/javascript"></script>
    Note: <script> tag will go inside <head> tag on HTML page.
Before We Get Started,
Scoping of Variables
Any variables created in any other block of code (code surrounded by curly brackets) will be considered global.
Example: Variables that are part of an if statement are not local to the if statement, it is considered as a global variable.
Global Variable Scope
  1. var color = "blue";
  2. if (color)
  3. {
  4. var color = "purple"; // this is a global variable,so color will changed to purple.
  5. console.log(color); // this statement will print purple
  6. }
  7. console.log(color); // this statement will print purple
As you can see the color variable in the if statement is global and though it is declared as new a variable in the if statement, it is not considered local because it is not in a function.
Local Variable Scope
  1. var color = "blue";
  2. function printColor()
  3. {
  4. var color = "purple"; // this is a local variable
  5. console.log(color); // this statement will print purple
  6. }
  7. printColor();
  8. console.log(color); // this statement will print blue
As you can see the local color variable is labeled as purple, and is only purple within the printColor function.
Though both the local and global variable has the same name, the local variable will take precedence over the global variable in the printColor function
Functions in JavaScript
Example:
  1. var x = 3;
  2. function numSquare(x)
  3. {
  4. return x * x;
  5. }
When you run this code, you will get 9 as output.
As we know that function can do different things. Assign one variable result into another variable.
Example 1:
  1. var x = 3;
  2. function numSquare(x)
  3. {
  4. return x * x;
  5. }
  6. var sentence = "The Square of " + x + " is equal to " + numSquare(x);
  7. console.log(sentence);
When you run this code
Output: The Square of 3 is equal to 9
Example 2:
  1. var num = numSquare(5);
  2. console.log(num);
When you run this code
Output: 36
Self Invoking Function
  1. A Special type of function that can be created within JavaScript.
  2. These functions run automatically. No call to the function needed.
  3. They can be anonymous or not.
  1. ((function selfPrint()
  2. {
  3. console.log("This function will automatically print this statement);
  4. })());
  5. //Be sure to wrap the function in parentheses and add another pair of parentheses at the end of the function.