Javascript is a light weight, object oriented programming language used for web development.
It is currently the most popular programming language
in the world as of 2018 according to the annual StackOverflow survey.
In addition, highly popular frameworks such as
React
and
Angular
are all javascript based. With
Node.js
you can run javascript
on the backend, making it a language you can use in both the front and backend of development.
Javascript is the programming language of the web
and it shows no sign of slowing down in popularity or development anytime soon.
Javascript is the main tool for the modern front end web developer. It is used to create interactive and dynamic websites that users can interact with. Learning and understanding the basics of plain vanilla javascript is crucial before developing in frameworks such as React, Angular or run-time environments like Node.js.
Before getting started with writing
Hello World
in javascript you will need solid a text editor. A recommended and popular modern text editor is
Visual Studio Code.
Inside this text editor, you can copy and paste the following code below. Inside the script tag, below the closing body tag, is where the js file is typically inserted inside the html document.
You can also create a standard html document by writing
doc
then hitting the
tab
key. This will create a standard HTML template like the one shown below without the script tag.
Note: "src" stands for source which is the location of your standard js file.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Some title
<meta name="This is intro to JS" content="Vanilla JS">
<meta name="author" content="Dash-intel">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<!-- connects your js and index.html file-->
<script src="js/scripts.js"> </script>
</body>
</html>
The javascript of your webpage is typically stored in a different file than the typical
index.html file. Step 1: Create a folder called
js right next to your index.html file. Inside this
folder create a file called
scripts.js
You can now connect your javascript and index.html files with the following html line of code.
<script src="js/scripts.js"> </script>
With the set up out of the way, you can test it out with your first line of javascript:
console.log('hello world');
To see this in the browser:
You should see Hello World printed on the screen. Still stuck? Try the following resource: How to set up Javascript
Another simple way to check to see everything is linked up and working is using the alert keyword. A msg box should pop up on the screen.
alert('hello world');
// Note: alert is a build-in function in javascript.
Comments are created using // for single line comments and /**/ for multi-line comments. Comments let you document your code so that others can better understand your code. Code that is commented will not run.
// This is for a single line comment
/* This is for
multiple line comments
in javascript
*/
Variables let you store data. There are many different types of data. The data types in javascript are
var name = 'Sara';
console.log(name); //Sara
var age = 25; //25
var isFemale = true; //true
var numberOfChildren = null; //null
var jim; // undefined
1. The convention for naming variables is to use camel casing.
isFemale and numberOfChildren are examples of camel casing.
2. We did not assign a value to the variable jim. Unassigned values get automatically assigned the a value of undefined. We can still use this variable later on and assign it a different value.
What exactly are variables? Variables are an address to a memory location. Variables let you store information (ie. values) in a computers memory which you are later able to retrieve when you call that variable. Variables allow for the storage and retrieval of values. This storage is at a specific location in a computers memory.
We can combine variables together in javascript even if these variables are not the same data type. For example:
var name = 'Sara';
var age = 25;
console.log(age + age); // 50
console.log(name + ' ' + name); // Sara Sara
console.log(name + 25); // Sara25
The final output is converted to a string. This is an example of data type coercion
The following operators are:
var name = 'Sara';
var age = 25;
console.log( (age*2) + 5); // 55
console.log( 11%7 ); // 4
console.log(2**5); // 32
console.log(name*3); // NaN
The final output is not a number, since javascript expects a number not a string to be multiplied.
In the first example, using brackets helps you define the order of operations.
The Logical operators are:
=== is usually faster than == and the first one in general is recommended to use.
Using == might result in unintended type coercion which may be difficult to debug.
var name = 'Sara';
var age = 26;
var ageString = '26';
var gender = 'female';
console.log(age < 30 && gender === 'female'); //true
console.log(age< 30 && gender === 'male'); //false
console.log(age< 30 || gender === 'male'); //true
console.log(age == ageString); //true
console.log(age === ageString); //false
Using if, else if and else enables your code to branch out. This allows you to check a certain condition or criteria and only run that line of code, if that condition is met.
If the first if statement is true, the expression will be executed and only that line of code will run.
Otherwise, it will keep checking the other else if statements. If none of them are true, the else statment gets executed and the corresponding line of code will be returned.
var yearOfBirth = 1995;
if (yearOfBirth > 1999){
console.log('generation z');
}
else if (yearOfBirth > 1980){
console.log('generation y');
}
else if (yearOfBirth > 1961){
console.log('generation x');
}
else if (yearOfBirth > 1946){
console.log('generation baby boomers');
}
else {
console.log('other generation');
}
// expected output: generation y
Functions are used when you need to do a certain task or procedure over and over again. Put simply, a function is a block of code that does a certain task. Instead of writing that block of code over and over again, we write functions to simplify and reduce the amount of code written.
Basic syntax for functions:
// Define a function called hello which prints out `hello world`
var hello = function(){
console.log('hello world');
}
hello(); // calling the function
// expected output: hello world;
You can call the hello function as many times as you like.
Here we have assigned a function to the variable hello. Typically function declarations are used when creating functions. This syntax is illustrated later on.
A main feature of functions are to return something. Return is a reserved keyword in javascript to do just that. For example:
var anotherFunction = function(){
var greeting = 'hello world';
return greeting;
}
// calling the function and logging it to the console.
console.log(anotherFunction()); // expected output: hello world;
Whenever you create a function using a variable, you must later call the function in order for something to happen.
Note: The variable greeting exists only inside the function. For example, if you try to console.log(greeting) on the last line above, you will get an undefined variable error. This is referred to as scope. A good way to think about scope, is that anything inside the function is not visible to the outside world. Ie. function create their own little universes. However, functions have access to variables on the outside, and variables that we pass into functions are referred to as parameters.
Global variables are variables outside the function scope. They are called global variables because any functions has access to it and can manipulate it's values. The next example combines functions and conditional statements.
var timeOfDay = 'morning'; // global variable
var greetingFunction = function(){
if(timeOfDay === 'morning'){
console.log('good morning');
}
else if(timeOfDay === 'afternoon'){
console.log('good afternoon');
}
else{
console.log('good evening');
}
}
greetingFunction(timeOfDay); // expected output: good morning
Parameters are variables that are passed into a function. You can thing of a parameter as an input to a function. Depending on the parameter a different output is created when you run the function. A function can have multiple parameters as well. Here is an example.
var greetingFunction = function(timeOfDay){
if(timeOfDay === 'morning'){
console.log('good morning');
}
else if(timeOfDay === 'afternoon'){
console.log('good afternoon');
}
else{
console.log('good evening');
}
}
greetingFunction('morning'); // good morning
Note: Parameters are also called arguments and are often used interchangeablely.
Functions with multiple parameters. That means multiple inputs into a function to create a single output.
Example 1:
//create a function with multiple inputs
var greetingFunction = function(name,timeOfDay){
if(timeOfDay === 'morning'){
console.log('good morning' + ' ' + name);
}
else if(timeOfDay === 'afternoon'){
console.log('good afternoon' + ' ' + name);
}
else{
console.log('good evening' + ' ' + name );
}
}
greetingFunction('Hannah','afternoon'); // good afternoon + ' ' + Hannah
Example 2:
//create a function with multiple inputs
var add = function(a,b){
return a + b;
}
console.log(add(2,4)) // expected output: 6;
Anonymous functions are functions without a name. For instance:
//create a function with multiple inputs
function(a,b){
return a + b;
}
//An Anonymous function
A function expression is a fancy way of referring to an anonymous functions that is assigned to a variable. For instance:
//A function expression
var add1 = function(a,b){
return a + b;
}
// a function expression.
Note: If you call the function add1 before the function expression, you get an undefined TypeError.
This is because function expressions are not hoisted. Hoisting refers to the way javascript is executed. The take away is if something is not hoisted, then you must define it before calling it.
add1(2,1); // expected output: TypeError: add1 is not a function
var add1 = function(a,b){
return a + b;
}
Function Declarations are functions that have names. I.e they are named functions. Because they are named functions, they are not assigned to a variable. An example of a function declaration:
add2(2,1); // expected output: 3;
function add2 (a,b){
return a + b;
}
// add2 is an example of a function declaration.
// It can be called before the named function.
Function declarations are hoisted. Because they are hoisted, you can call the function at the top of your code before the function is declared. A function statement and a function declaration are often used to refer to the same thing.
Function constructors create
blueprints for an object.
A function constructor , object constructor or function object constructor
all refer to the same thing.
Regardless of how you call them, function constructors create blueprints for objects. This is useful when you need to create many
similar instances of objects that share many similar
properties or
methods.
// Creating function constructors
// Here is an example of creating a Person object using the function constructor method.
// We name function constructors starting with a Capital letter by convention.
// This is to distinguish function contstructors from regular objects and functions.
//Create a `Person` function constructor
function Person(name,age,netWorth,gender){
this.name = name;
this.age = age;
this.netWorth = netWorth;
this.gender = gender;
}
const mark = new Person('Mark',34,'74 billion','male'); // a new Person object `mark` was created.
console.log(mark);
// we can add a property to the existing Person object of mark.
mark.nationality = 'American'; // this nationality is unique to the mark object only.
console.log(mark);
// we can add a new method to the existing Person object or mark.
mark.greeting = () =>{
console.log(`Hi my name is ${mark.name} and I am CEO bitch`); // this greeting is unique to mark.
}
// calling the greeting function
mark.greeting();
// we can add additional properties or method to the Person function constructor anytime.
// Example
function Person(name,age,netWorth,gender){
this.name = name;
this.age = age;
this.netWorth = netWorth;
this.gender = gender;
this.greeting = ()=>{
console.log(`Hi my name is ${this.name}!`);
}
}
const jeff = new Person('Jeff Bezos', 54,'100 billion','male');
console.log(jeff); // we see the jeff object does not have the `nationality` property.
// calling the greeting method.
jeff.greeting();
// over writing the greeting method with a personalized `jeff` greeting method
jeff.greeting = ()=>{
console.log(`Hi my name is ${jeff.name} but you can call me king Bezos! `);
}
// calling the updated `jeff` greeting method
jeff.greeting();
You can also refer to here for a more indepth explanation.