Introduction to JavaScript
Hey, there Let’s learn what’s so unique about JavaScript…
WHY JAVASCRIPT?
So, people often ask this question “why JavaScript?!” and not some other programming language. Well, the answer to this question is pretty easy because today, JavaScript is the language that powers the entire internet. It allows developers to add complexity, and dynamics to websites and web apps and it also allows the usage of some popular frameworks like React.js, Angular.js, Vue.js, and Node.js to build even more advanced web applications. Now, all of these require a deep share of JavaScript knowledge but sometimes JavaScript can be difficult to learn. Not to worry, once you learn the basics like variables, functions, arrays, data types, control flows, objects, etc. you are good to go!
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.
What can JavaScript do?
Control Browsers & Identify user activity & Validate Data
Control HTML Attributes, Tags & Elements
Control CSS Styles & Properties
Find Components using the CSS selector
Detecting a Mouse/Keyboard event
Manage Cookies, localStorage & Browser memory
Lightweight
JavaScript being a lightweight language just means that it doesn’t use much memory of the computer. It has a relatively simple syntax and features.
Cross-platform
Being cross-platform just means the language can be used in different platforms and systems.
Object-oriented
Then being an objected-oriented language means that is a language that is based on objects.
Now, apart from HTML and CSS , JavaScript is one of the three core technologies of web development and it is most commonly used as a part of webpages but it is also used on environments that are not web based.
Initially, JavaScript was a client-side language only but today it is both a client-side and server-side language thanks to node.js, we can use JavaScript on the server as well.
WHERE DOES JAVASCRIPT FIT IN?
Am sure you already know that HTML is responsible for holding the content of a webpage and CSS is responsible for styling this content and the layout, then JavaScript is a programming language that allows us to add dynamics to the webpage, things like dynamic effects, manipulation of the content, etc.
We can also explain it in the terms of nouns, adjectives and verbs.
NOUNS
<p></p>;
means “paragraph”. so here the HTML does the noun like saying that the P element is a paragraph
ADJECTIVES
p {color: red;}
means “the paragraph text is red”. Now the CSS is the Adjective because it describes the noun like saying the paragraph is red.
VERBS
p.hide();
means “hide the paragraph”. finally JavaScript is the verb like saying hide the paragraph, so basically we are performing an action on the paragraph tag.
In order to write our JavaScript code we need a place to write the code and that’s inside the script tag in the HTML file or you can create an external JavaScript file and link it to your HTML file.
Features of JavaScript
- Object-Centered Script Language.
- Client edge Technology.
- Validation of User’s Input.
- Else and If Statement.
- Interpreter Centered.
- Ability to perform In Built Function.
- Case Sensitive format.
- Light Weight and delicate.
Javascript Attributes and properties
document.body.sayTagName = function() {
alert(this.tagName);
};
document.body.sayTagName(); // BODY (the value of "this" in the method is document.body)We can also modify built-in prototypes like Element.prototype and add new methods to all elements:
Element.prototype.sayHi = function() {
alert(`Hello, I'm ${this.tagName}`);
};
document.documentElement.sayHi(); // Hello, I'm HTML
document.body.sayHi(); // Hello, I'm BODYSo, DOM properties and methods behave just like those of regular JavaScript objects:
- They can have any value.
- They are case-sensitive (write
elem.nodeType, notelem.NoDeTyPe).
HTML attributes
In HTML, tags may have attributes. When the browser parses the HTML to create DOM objects for tags, it recognizes standard attributes and creates DOM properties from them.
So when an element has id or another standard attribute, the corresponding property gets created. But that doesn’t happen if the attribute is non-standard.
For instance:
<body id="test" something="non-standard">
<script>
alert(document.body.id); // test
// non-standard attribute does not yield a property
alert(document.body.something); // undefined
</script>
</body>Please note that a standard attribute for one element can be unknown for another one. For instance, "type" is standard for <input> (HTMLInputElement), but not for <body> (HTMLBodyElement). Standard attributes are described in the specification for the corresponding element class.
Here we can see it:
<body id="body" type="...">
<input id="input" type="text">
<script>
alert(input.type); // text
alert(body.type); // undefined: DOM property not created, because it's non-standard
</script>
</body>So, if an attribute is non-standard, there won’t be a DOM-property for it. Is there a way to access such attributes?
Sure. All attributes are accessible by using the following methods:
elem.hasAttribute(name)– checks for existence.elem.getAttribute(name)– gets the value.elem.setAttribute(name, value)– sets the value.elem.removeAttribute(name)– removes the attribute.
These methods operate exactly with what’s written in HTML.
Also one can read all attributes using elem.attributes: a collection of objects that belong to a built-in Attr class, with name and value properties.
Get Elvis Edeh’s stories in your inbox
Join Medium for free to get updates from this writer.
Here’s a demo of reading a non-standard property:
<body something="non-standard">
<script>
alert(document.body.getAttribute('something')); // non-standard
</script>
</body>HTML attributes have the following features:
- Their name is case-insensitive (
idis same asID). - Their values are always strings.
Here’s an extended demo of working with attributes:
<body>
<div id="elem" about="Elephant"></div>
<script>
alert( elem.getAttribute('About') ); // (1) 'Elephant', reading
elem.setAttribute('Test', 123); // (2), writing
alert( elem.outerHTML ); // (3), see if the attribute is in HTML (yes)
for (let attr of elem.attributes) { // (4) list all
alert( `${attr.name} = ${attr.value}` );
}
</script>
</body>Please note:
getAttribute('About')– the first letter is uppercase here, and in HTML it’s all lowercase. But that doesn’t matter: attribute names are case-insensitive.- We can assign anything to an attribute, but it becomes a string. So here we have
"123"as the value. - All attributes including ones that we set are visible in
outerHTML. - The
attributescollection is iterable and has all the attributes of the element (standard and non-standard) as objects withnameandvalueproperties.
Property-attribute synchronization
When a standard attribute changes, the corresponding property is auto-updated, and (with some exceptions) vice versa.
In the example below id is modified as an attribute, and we can see the property changed too. And then the same backwards:
<input>
<script>
let input = document.querySelector('input');
// attribute => property
input.setAttribute('id', 'id');
alert(input.id); // id (updated)
// property => attribute
input.id = 'newId';
alert(input.getAttribute('id')); // newId (updated)
</script>But there are exclusions, for instance input.value synchronizes only from attribute → property, but not back:
<input>
<script>
let input = document.querySelector('input');
// attribute => property
input.setAttribute('value', 'text');
alert(input.value); // text
// NOT property => attribute
input.value = 'newValue';
alert(input.getAttribute('value')); // text (not updated!)
</script>In the example above:
- Changing the attribute
valueupdates the property. - But the property change does not affect the attribute.
That “feature” may actually come in handy, because the user actions may lead to value changes, and then after them, if we want to recover the “original” value from HTML, it’s in the attribute.
DOM properties are typed
DOM properties are not always strings. For instance, the input.checked property (for checkboxes) is a boolean:
<input id="input" type="checkbox" checked> checkbox
<script>
alert(input.getAttribute('checked')); // the attribute value is: empty string
alert(input.checked); // the property value is: true
</script>There are other examples. The style attribute is a string, but the style property is an object:
<div id="div" style="color:red;font-size:120%">Hello</div>
<script>
// string
alert(div.getAttribute('style')); // color:red;font-size:120%
// object
alert(div.style); // [object CSSStyleDeclaration]
alert(div.style.color); // red
</script>Most properties are strings though.
Quite rarely, even if a DOM property type is a string, it may differ from the attribute. For instance, the href DOM property is always a full URL, even if the attribute contains a relative URL or just a #hash.
Here’s an example:
<a id="a" href="#hello">link</a>
<script>
// attribute
alert(a.getAttribute('href')); // #hello
// property
alert(a.href ); // full URL in the form http://site.com/page#hello
</script>If we need the value of href or any other attribute exactly as written in the HTML, we can use getAttribute.
Non-standard attributes, dataset
When writing HTML, we use a lot of standard attributes. But what about non-standard, custom ones? First, let’s see whether they are useful or not? What for?
Sometimes non-standard attributes are used to pass custom data from HTML to JavaScript, or to “mark” HTML-elements for JavaScript.
Like this:
<!-- mark the div to show "name" here -->
<div show-info="name"></div>
<!-- and age here -->
<div show-info="age"></div>
<script>
// the code finds an element with the mark and shows what's requested
let user = {
name: "Pete",
age: 25
};
for(let div of document.querySelectorAll('[show-info]')) {
// insert the corresponding info into the field
let field = div.getAttribute('show-info');
div.innerHTML = user[field]; // first Pete into "name", then 25 into "age"
}
</script>Also, they can be used to style an element.
For instance, here for the order state the attribute order-state is used:
<style>
/* styles rely on the custom attribute "order-state" */
.order[order-state="new"] {
color: green;
}
.order[order-state="pending"] {
color: blue;
}
.order[order-state="canceled"] {
color: red;
}
</style>
<div class="order" order-state="new">
A new order.
</div>
<div class="order" order-state="pending">
A pending order.
</div>
<div class="order" order-state="canceled">
A canceled order.
</div>Why would using an attribute be preferable to having classes like .order-state-new, .order-state-pending, .order-state-canceled?
Because an attribute is more convenient to manage. The state can be changed as easy as:
// a bit simpler than removing old/adding a new class
div.setAttribute('order-state', 'canceled');But there may be a possible problem with custom attributes. What if we use a non-standard attribute for our purposes and later the standard introduces it and makes it do something? The HTML language is alive, it grows, and more attributes appear to suit the needs of developers. There may be unexpected effects in such case.
To avoid conflicts, there exist data-* attributes.
All attributes starting with “data-” are reserved for programmers’ use. They are available in the dataset property.
For instance, if an elem has an attribute named "data-about", it’s available as elem.dataset.about.
Like this:
<body data-about="Elephants">
<script>
alert(document.body.dataset.about); // Elephants
</script>Multiword attributes like data-order-state become camel-cased: dataset.orderState.
Here’s a rewritten “order state” example:
<style>
.order[data-order-state="new"] {
color: green;
}
.order[data-order-state="pending"] {
color: blue;
}
.order[data-order-state="canceled"] {
color: red;
}
</style>
<div id="order" class="order" data-order-state="new">
A new order.
</div>
<script>
// read
alert(order.dataset.orderState); // new
// modify
order.dataset.orderState = "pending"; // (*)
</script>Using data-* attributes is a valid, safe way to pass custom data.
Please note that we can not only read, but also modify data-attributes. Then CSS updates the view accordingly: in the example above the last line (*) changes the color to blue.
Summary
- Attributes — is what’s written in HTML.
- Properties — is what’s in DOM objects.
A small comparison:
JavaScript Advantages
Client-Side execution with Rich interfaces, Simplicity & Speed
User Interface Interactivity with Extended Functionality
Rapid Development with new version Updates
Browser Compatible
Make XMLHttpRequest() Object
JavaScript Limitation
Code Always Visible to end-users
sometimes slow execution
Stop Rendering if an error occurs from the server
SUMMARY
JavaScript is what made modern web development possible: it allows us to add Dynamic effect and interactivity to our websites and also helps to develop a complex modern web app that we can interact with. today there are many JavaScript libraries and frameworks out there that implement different architectures and help developers in building complex apps easily and faster (e.g JQUERY,ANGULAR.JS, REACT).
So basically JavaScript is a fun, interesting programming language….what are you waiting for?!!! get yourself ready and start coding…
Hope this was helpful to you. If it was, then don’t forget to clap and leave a comment.




