473,287 Members | 1,827 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,287 developers and data experts.

What is JavaScript?

JavaScript is a dynamic programming language that's used for web development, in web applications, for game development, and lots more. It allows you to implement dynamic features on web pages that cannot be done with only HTML and CSS.

Many browsers use JavaScript as a scripting language for doing dynamic things on the web. Any time you see a click-to-show dropdown menu, extra content added to a page, and dynamically changing element colors on a page, to name a few features, you're seeing the effects of JavaScript.

What Would the Web Look Like Without JavaScript?
Without JavaScript, all you would have on the web would be HTML and CSS. These alone limit you to a few web page implementations. 90% (if not more) of your webpages would be static, and you'd only have the dynamic changes like animations that CSS provides.

How JavaScript Makes Things Dynamic
HTML defines the structure of your web document and the content therein. CSS declares various styles for the contents provided on the web document.

HTML and CSS are often called markup languages rather than programming languages, because they, at their core, provide markups for documents with very little dynamism.

JavaScript, on the other hand, is a dynamic programming language that supports Math calculations, allows you to dynamically add HTML contents to the DOM, creates dynamic style declarations, fetches contents from another website, and lots more.

Before we go into how JavaScript does all of these things, let's look at a quick example.

Check out this codepen: https://codepen.io/Dillion/full/XWjvdMG

In the codepen, you'll see that as you type in the input field, the text shows on the screen. That is made possible by JavaScript. You cannot get this with HTML, CSS, nor both of them together.

JavaScript can do a lot more than what I can cover in this article. But to get you started with JS, we'll look at:

how to use JavaScript in HTML
data types
variables
comments
functions
How to Use JavaScript in HTML
Just like with CSS, JavaScript can be used in HTML in various ways, such as:

1. Inline JavaScript
Here, you have the JavaScript code in HTML tags in some special JS-based attributes.

For example, HTML tags have event attributes that allow you to execute some code inline when an event is triggered. Here's what I mean:

Expand|Select|Wrap|Line Numbers
  1. <button onclick="alert('You just clicked a button')">Click me!</button>
  2. This is an example of inline JavaScript. The value of onclick can be some Match calculation, a dynamic addition to the DOM – any syntax-valid JavaScript code.
2. Internal JavaScript, with the script tag
Just like the style tag for style declarations within an HTML page, the script tag exists for JavaScript. Here's how it's used:

Expand|Select|Wrap|Line Numbers
  1. <script>
  2.     function(){
  3.         alert("I am inside a script tag")
  4.     }
  5. </script>
3. External JavaScript
You may want to have your JavaScript code in a different file. External JavaScript allows this. For such uses-cases, here's how it's done:

Expand|Select|Wrap|Line Numbers
  1. <!-- index.html -->
  2. <script src="./script.js"></script>
  3. // script.js
  4. alert("I am inside an external file");
The src attribute of the script tag allows you to apply a source for the JavaScript code. That reference is important because it notifies the browser to also fetch the content of script.js.

script.js can be in the same directory with index.html, or it can be gotten from another website. For the latter, you'll need to pass the full URL (https://.../script.js).

Notice the .js extension? That's the extension for JavaScript files, just like HTML has .html.

Now that we've looked at ways to apply JavaScript to our HTML, let's look at some of the features of JavaScript.

Data Types in JavaScript
In JavaScript, data has to be of one type or another. JavaScript needs to know this so that it knows how to use it with other data or how to operate on such data.

Here are the basic data types that JavaScript supports:
  • Number (for example, 6, 7, 8.9): on which you can apply arithmetic operations (like addition) and many more
  • String (like "javascript", 'a long sentence', a short paragraph): anything found between single quotes ('...'), double quotes ("...") and backticks (...). There's no difference between single and double quotes, but backticks have more features, such as:
  • interpolating variables in strings, like so: My name is ${name}. name here is a variable, injected into the string.
  • multiline strings. With normal quotes, you'd need to add escape characters like \n for a newline, but backticks allow you to continue your string on another line, like so:
  • let str = `I am a
  • multiline string`;
  • Boolean (can only be of two values: true or false): more like yes (true) or no (false)
  • Array (for example, [1, 2, "hello", false]): a group of data (which can be of any type, including arrays) separated by a comma. Indexing starts from 0. Accessing the content of such a group can be like so: array[0], which for this example will return 1, since it's the first item.
  • Object (for example {name: 'javascript', age: 5}): also a group of data but in the form of a key:value pair. The key has to be a string, and the value can be any type including another object. Accessing the content of the group is done with the key, for example obj.age or obj["age"] will return 5.
  • Undefined (the only data this type supports is undefined): This data can be assigned to a variable explicitly, or implicitly (by JavaScript) if a variable has been declared but not assigned a value. Later in this article, we'll look at variable declaration and value assignment.
  • Null (the only data this type supports is null): Null means there is no value. It holds a value, but not a real value – rather, null.
  • Function (for example, function(){ console.log("function") }): A function is a data type that invokes a block of code when called. More on functions later in this article.
  • JavaScript data types can be a bit complicated to understand. You may have heard that arrays and functions are also objects, and that's true.

Understanding this involves understanding the nature of JavaScript prototypes. But, at the basic level, these are the data types you need to know first in JavaScript.

Variables in JavaScript
Variables are containers for values of any data type. They hold values such that when the variables are used, JavaScript uses the value they represent for that operation.

Variables can be declared and can be assigned a value. When you declare a variable, you're doing this:

let name;
For the above, name has been declared, but it doesn't have a value yet.

As you'd expect from the data types section, JavaScript automatically assigns a value of undefined to name. So if you try to use name anywhere, undefined will be used for that operation.

Here's what it means to assign a value to a variable:

Expand|Select|Wrap|Line Numbers
  1. let name;
  2. name = "JavaScript";
Now if you use name, it will represent JavaScript.

Declarations and assignments can be done on one line like so:

let name = "JavaScript";
Why let? you may have asked yourself, and here's why: JavaScript supports three methods of variable declarations, which are:

the var operator: this has been with JavaScript since its inception. You can declare variables and assign values to them which can be changed later in the code. Here's what I mean:
var name = "JavaScript";
name = "Language";
the let operator: this is also very similar to var – it declares and assigns values to variables that can be changed later in the code. The major difference between these operators is that var hoists such variables, while let does not hoist. The concept of hoisting can be explained briefly with the following code:
Expand|Select|Wrap|Line Numbers
  1. function print() {
  2.     console.log(name);
  3.     console.log(age);
  4.     var name = "JavaScript";
  5.     let age = 5;
  6. }
  7.  
  8. print();
On calling the print function (print()), the first console.log prints undefined while the second console.log throws an error that it "Cannot access age before initialization".

This is because the name variable's declaration is hoisted (raised) to the top of the function and the assignment for the variable stays at the same line while the age declaration and assignment stays at the same line.

Here's how the above code is compiled:

Expand|Select|Wrap|Line Numbers
  1. function print() {
  2.     var name;
  3.     console.log(name);
  4.     console.log(age);
  5.     name = "JavaScript";
  6.     let age = 5;
  7. }
  8.  
  9. print();
Hoist problems can happen unexpectedly, and that's why you should use let instead of var.

the const operator: this also does not hoist variables, but it does one more thing: it ensures that a variable cannot be assigned another value other than what it was assigned during initialization.
For example:

let name = "JavaScript"
name = "Language" // no errors

const age = 5
age = 6 // error, cannot reassign variable
Comments in JavaScript
Just like HTML, sometimes we may want to put a note beside our code which does not need to be executed.

We can do this in JavaScript in two ways:

with single-line comments, like this: // a single line comment
or with multi-line comments, like this:
Expand|Select|Wrap|Line Numbers
  1. /*
  2. a multi
  3. line comment
  4. */
Functions in JavaScript
With functions, you can store a block of code that can be used in other places in your code. Say you wanted to print "JavaScript" and "Language" at different places in your code. Instead of doing this:

Expand|Select|Wrap|Line Numbers
  1. console.log("JavaScript")
  2. console.log("Language")
  3.  
  4. // some things here
  5.  
  6. console.log("JavaScript")
  7. console.log("Language")
  8.  
  9. // more things here
  10.  
  11. console.log("JavaScript")
  12. console.log("Language")
  13. You can do this:
  14.  
  15. function print() {
  16.     console.log("JavaScript")
  17.     console.log("Language")
  18. }
  19.  
  20. print()
  21.  
  22. // some things here
  23.  
  24. print()
  25.  
  26. // more things here
  27.  
  28. print()
This way, we've stored the repeated code block in a function that can be used wherever we want. But that's not all. Say we wanted to find the average of three numbers. The code for this would be:

Expand|Select|Wrap|Line Numbers
  1. let num1 = 5
  2. let num2 = 6
  3. let num3 = 8
  4. let average = (num1 + num2 + num3) / 3
Doing this outside of a function may not hurt, but if we had to do that in many places? Then, we'd have a function like so:

Expand|Select|Wrap|Line Numbers
  1. function findAverage(n1, n2, n3) {
  2.     let aver = (n1 + n2 + n3) / 3
  3.     return aver
  4. }
  5.  
  6. let num1 = 5
  7. let num2 = 6
  8. let num3 = 8
  9. let average = findAverage(num1, num2, num3)
  10.  
  11. // later on, somewhere else
  12. let average2 = findAverage(...)
  13.  
  14. // later on, somewhere else
  15. let average3 = findAverage(...)
As you'll notice in findAverage's declaration, we have n1, n2, n3 in the parentheses. These are parameters, which serve as placeholders for values that would be provided when the function is to be called.

The code block uses those placeholders to find the average, and the return keyword returns the average from the function.

Placeholders make your functions reusable such that different values at different times can be passed to the functions to use the same logic.

Conclusion
JavaScript has many more features we could discuss, but I hope this article has given you a clear starting point to go further. Now you should know what the language is and how you can use it on the web.

In this article, we've looked at how to add JavaScript code to our HTML files, the different types of data that JavaScript supports, variables that serve as containers for values, how to write comments in JavaScript, and a little bit about how to declare and use functions.

There are so many places to go from here, but I'd recommend learning about The DOM and how JavaScript interacts with it next.
Jul 16 '21 #1
1 4268
Thanks for sharing such a good information. it will help me to learn javascript
Jul 19 '21 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

53
by: Cardman | last post by:
Greetings, I am trying to solve a problem that has been inflicting my self created Order Forms for a long time, where the problem is that as I cannot reproduce this error myself, then it is...
145
by: Mark Johnson | last post by:
Oddly enough, I found it difficult, using Google, to find a list of best-of sites based on the quality of their css packages. So I'd ask. Does anyone know of particularly good sites which are in...
25
by: Jeff | last post by:
Use the MS Script Editor included free with MS Office 2002 and above, for debugging Internet Explorer (IE). This subject is of great interest to many JS developers, as there is no obvious, low...
16
by: zwetan | last post by:
Hi, often I see people telling that "javascript sucks" - is it because of the DOM with JS ? - is it because of the language in itself ? - is it because browsers/hosts differences ? - is it...
104
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from...
5
by: Alfred | last post by:
Any solid javascript library available that has a splitter bar, drag & drop and treeview for a site that contains only dynamically created controls served thru a local webservice? TIA
6
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - I have <a href="javascript:somefunction()"what .... ?...
12
by: pantagruel | last post by:
Hi, I'm thinking of making a WScript based JavaScript library, I can think of some specific non-browser specific scripting examples that should probably make it in, like Crockford's little...
6
by: Chris Curvey | last post by:
Hi All, I have inherited a web page that includes lots of javascript. When I click on some things, the CPU utilization on the browser machine goes to 100% and the browser becomes unresponsive...
34
by: dhtml | last post by:
I made a change to the FAQ of javascript to EcmaScript. I got some feedback that the newsgroup is CLJ and the language is commonly referred to as JavaScript. Therefore, the word in the FAQ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.