DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for INTRODUCTION TO JAVASCRIPT.
viola kinya kithinji
viola kinya kithinji

Posted on

INTRODUCTION TO JAVASCRIPT.

What is Javascript JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). There are also more advanced server side versions of JavaScript such as Node.js, which allow you to add more functionality to a website than downloading files (such as real-time collaboration between multiple computers). Inside a host environment (for example, a web browser), JavaScript can be connected to the objects of its environment to provide programmatic control over them. It's standard libraries of objects are :Arrays, Date and math, it also have a core set of language elements such as: operators, control structures and structures. Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects; for example:

1:Client-side JavaScript- extends the core language by supplying objects to control a browser and its Document Object Model (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.
2:Server-side JavaScript- extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation to another of the application, or perform file manipulations on a server.
This means that in the browser, JavaScript can change the way the webpage (DOM) looks. And, likewise, Node.js JavaScript on the server can respond to custom requests from code written in the browser.

Getting started with Javascript
Getting started with JavaScript is easy: all you need is a modern Web browser. This guide includes some JavaScript features which are only currently available in the latest versions of Firefox, so using the most recent version of Firefox is recommended.

The Web Console tool built into Firefox is useful for experimenting with JavaScript; you can use it in two modes: single-line input mode, and multi-line input mode.

Single-line input in the Web Console

The Web Console shows you information about the currently loaded Web page, and also includes a JavaScript interpreter that you can use to execute JavaScript expressions in the current page.

To open the Web Console (Ctrl+Shift+I on Windows and Linux or Cmd-Option-K on Mac), open the Tools menu in Firefox, and select "Developer β–Ά Web Console".

The Web Console appears at the bottom of the browser window. Along the bottom of the console is an input line that you can use to enter JavaScript, and the output appears in the panel above:

Image description

The console works the exact same way as eval: the last expression entered is returned. For the sake of simplicity, it can be imagined that every time something is entered into the console, it is actually surrounded by console.log around eval, like so:

console.log(eval('3 + 5'))
Enter fullscreen mode Exit fullscreen mode

Multi-line input in the Web Console

The single-line input mode of the Web Console is great for quick testing of JavaScript expressions, but although you can execute multiple lines, it's not very convenient for that. For more complex JavaScript, you can use the multi-line input mode.

Hello world
To get started with writing JavaScript, open the Web Console in multi-line mode, and write your first "Hello world" JavaScript code:

(function(){
  "use strict";
  /* Start of your code */
  function greetMe(yourName) {
    alert('Hello ' + yourName);
  }

  greetMe('World');
  /* End of your code */
})();
Enter fullscreen mode Exit fullscreen mode

Press Cmd+Enter or Ctrl+Enter (or click the Run button) to watch it unfold in your browser!
Remember to always include the (function(){"use strict"; before your code, and add })(); to the end of your code. The strict mode and IIFE articles explain what those do, but for now they can be thought of as doing the following:

Prevent semantics in JavaScript that trip up beginners.
Prevent code snippets executed in the console from interacting with one-another (e.g., having something created in one console execution being used for a different console execution).

VARIABLES
Are containers that store values. You start by declaring a variable with the let keyword, followed by the name you give to the variable:

let myVariable;
Enter fullscreen mode Exit fullscreen mode

A semicolon at the end of line, indicates end of a statement. Its crucial when you want to separate when you want to separate statement on a single-line. There are rules on when you will use and not use semicolons.
You can name your variables anything but there are restrictions. JavaScript is case sensitive you have to be careful when it comes to naming and calling your variables. You can give your variable a value as following:

myVariable ='Nick';
Enter fullscreen mode Exit fullscreen mode

You can do both these operations on a same line as follow:

let myVariable = 'Nick';
Enter fullscreen mode Exit fullscreen mode

You get the value by calling the variable as follows:

myVariable
Enter fullscreen mode Exit fullscreen mode

you can change the value of the variable after assigning by:

let myVariable ='Nick'
myVariable = 'Ndolo'

Enter fullscreen mode Exit fullscreen mode

NOTE
Variables may hold values with different data types: Example

Strings -This is a sequence of text known as a string. To signify that the value is a string, enclose it in single quote Eg let myVariable = 'Nick';
Numbers -This is a number. Numbers don't have quotes around them. Eg let myVariable = 10;

Boolean -This is a True/False value. The words true and false are special keywords that don't need quote marks.Eg let myVariable = true;

Arrays -This is a structure that allows you to store multiple values in a single reference.Eg let myVariable = [1,'Nick','Ndolo',10];
Refer to each member of the array like this:
myVariable[0], myVariable[1], etc.

Object -This can be anything. Everything in JavaScript is an object and can be stored in a variable. Keep this in mind as you learn.Eg let myVariable = document.querySelector('h1');
All of the above examples too.

      **Comments**
Enter fullscreen mode Exit fullscreen mode

Comments are snippets of text that can be added along with code. The browser ignores text marked as comments. You can write comments in JavaScript just as you can in CSS:

If your comment contains no line breaks, it's an option to put it behind two slashes like this:

/*
Everything in between is a comment
*/
Enter fullscreen mode Exit fullscreen mode

If your comment contains no line breaks, it's an option to put it behind two slashes like this:

This is a comment
Enter fullscreen mode Exit fullscreen mode

Operators
An operator is a mathematical symbol that produces a result based on two values (or variables). In the following table, you can see some of the simplest operators, along with some examples to try in the JavaScript console.

Addition(+)
Add two numbers together or combine two strings.Eg 'hello'+ 'world'

Subtraction, Multiplication and Division(-, *, /)
These do what you'd expect them to do in basic math. Eg 9 - 3;
8 * 2; // multiply in JS is an asterisk
9 / 3;

Assignment(=)
As you've seen already: this assigns a value to a variable. Eg
let myVariable = 'Nick';

Strictly Equal(===)
This performs a test to see if two values are equal. It returns a true/false (Boolean) result. Eg let myVariable = 3;
myVariable === 4;

Not, Does not-Equal
This returns the logically opposite value of what it precedes. It turns a true into a false, etc.. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal. Eg For "Not", the basic expression is true, but the comparison returns false because we negate it:

let myVariable = 3;
!(myVariable === 3);

"Does-not-equal" gives basically the same result with different syntax. Here we are testing "is myVariable NOT equal to 3". This returns false because myVariable IS equal to 3:

let myVariable = 3;
myVariable !== 3;

Note
Mixing data types can lead to some strange results when performing calculations. Be careful that you are referring to your variables correctly, and getting the results you expect. For example, enter '35' + '25' into your console. Why don't you get the result you expected? Because the quote marks turn the numbers into strings, so you've ended up concatenating strings rather than adding numbers. If you enter 35 + 25 you'll get the total of the two numbers.

Conditionals
Conditionals are code structures used to test if an expression returns true or not. A very common form of conditionals is the if ... else statement. For example:

let iceCream = 'chocolate';
if(iceCream === 'chocolate') {
  alert('Yay, I love chocolate ice cream!');
} else {
  alert('Awwww, but chocolate is my favorite...');
}


Enter fullscreen mode Exit fullscreen mode

The expression inside the if( ... ) is the test. This uses the strict equality operator (as described above) to compare the variable iceCream with the string chocolate to see if the two are equal. If this comparison returns true, the first block of code runs. If the comparison is not true, the second block of codeβ€”after the else statementβ€”runs instead.

Functions
are a way of packaging functionality that you wish to reuse. It's possible to define a body of code as a function that executes when you call the function name in your code. This is a good alternative to repeatedly writing the same code. You have already seen some uses of functions. For example

let myVariable = document.querySelector('h1');

alert('hello!');
Enter fullscreen mode Exit fullscreen mode

These functions, document.querySelector and alert, are built into the browser.

If you see something which looks like a variable name, but it's followed by parenthesesβ€” () β€”it is likely a function. Functions often take arguments: bits of data they need to do their job. Arguments go inside the parentheses, separated by commas if there is more than one argument.

For example, the alert() function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what message to display.

You can also define your own functions. In the next example, we create a simple function which takes two numbers as arguments and multiplies them:

function multiply(num1,num2) {
  let result = num1 * num2;
  return result;
}
Enter fullscreen mode Exit fullscreen mode

Try running this in the console; then test with several arguments. For example:

multiply(4, 7);
multiply(20, 20);
multiply(0.5,3);
Enter fullscreen mode Exit fullscreen mode

Note The return statement tells the browser to return the result variable out of the function so it is available to use. This is necessary because variables defined inside functions are only available inside those functions. This is called variable scoping. (Read more about variable scoping.)

Events
Real interactivity on a website requires event handlers. These are code structures that listen for activity in the browser, and run code in response. The most obvious example is handling the click event, which is fired by the browser when you click on something with your mouse. To demonstrate this, enter the following into your console, then click on the current webpage:

document.querySelector('html').addEventListener('click', function() {
  alert('Ouch! Stop poking me!');
});

Enter fullscreen mode Exit fullscreen mode

There are many ways to attach an event handler to an element. Here we select the element. We then call its addEventListener() function, passing in the name of the event to listen to ('click') and a function to run when the event happens.

Note that

document.querySelector('html').addEventListener('click', function() {
  alert('Ouch! Stop poking me!');
});

Enter fullscreen mode Exit fullscreen mode

Is equivalent to

let myHTML = document.querySelector('html');
myHTML.addEventListener('click', function() {
  alert('Ouch! Stop poking me!');
});
Enter fullscreen mode Exit fullscreen mode

It's just shorter.

The functions we just passed to addEventListener() here are called anonymous functions, because they don't have a name. There's an alternative way of writing anonymous functions, which we call an arrow function. An arrow function uses () => instead of function ():

Conculsion
In this article i have handled introduction to Javascript and javascript basics...Consistency is key.

Top comments (0)

DEV

Thank you.

Β 
Thanks for visiting DEV, we’ve worked really hard to cultivate this great community and would love to have you join us. If you’d like to create an account, you can sign up here.