JavaScript Object

JavaScript Object

In JavaScript we can create an object in various ways. In fact, to create an object in JavaScript we can also use other methods than what we saw in the previous lessons and in particular we can use the constructor object.

Examples of using JavaScript object

Let’s create an example where, to create an object, we use the new keyword together with the object () constructor.

let person = new Object();
person.name = "Coding";
person.lastname = "Creativo";
person.age = 30;

After creating the object instance we can define the various properties always using the dot notation, to which we will assign values.

Later we can view them simply by calling each property like this:

console.log(person.name);
console.log(person.lastname);
console.log(person.age);

You can also define methods, as we have seen in previous lessons, by assigning a function to an object property.

In our case we assign a function to the greet property that has the task of displaying an alert when called.

let person = new Object();
person.name ="Coding";
person.lastname = "Creativo";
person.age = 30;

persona.greet = function (){
  alert('Hello ' + person.name);
}

persona.greet();

Then by calling the greeting () method on our person object, the alert will appear with the appropriate greeting. Of course, the greeting method can also be called on another instance.

JavaScript Object – constructing an object from primitive data

In JavaScript it is possible to construct an object starting from a primitive data type, such as a number or a string.

let number = new Object(5.67895);
let str = new Object('Coding Creativo');

What you get then is a string or number object.

In fact, if we try to make the console log, we will see objects in our console.

console.log(number);
console.log(str);

Here is the result obtained in our console:

object in javascript

You can also see that it is an object simply by typing on number or on string:

console.log(typeof(number));

So we can for example use the toFixed () method on the object number.

So let’s add this line of code:

number = number.toFixed(2);

And then we do the console.log:

console.log(number);

Conclusion

In this lesson we have seen how to use in JavaScript the object constructor, in the next lesson we will deal with object oriented programming again.

Alcuni link utili

Indice argomenti tutorial JavaScript

JavaScript calculator

JavaScript calculator

In this article, we create a simple calculator with JavaScript, to further explain the getElementById () method.

This is also a simple exercise proposed for educational purposes, later we will develop the same exercise using jQuery.

JavaScript calculator – development

The simple calculator example we’re going to make today uses HTML, CSS, and even JavaScript.

Here is the example.

Enter the numbers and operations by clicking on the buttons and finally click on the equal button (=) to get the result of the operation. Now you can continue to operate on the number obtained or, if you want to delete all the contents of the display, click on the C button.

First we create the HTML code to insert the keys from 0 to 9, then we insert the buttons for the mathematical operations, the key for the comma, the C key and finally the equal key. We also insert the display at the top.

We will then use the div tags, the input tags and the button tag, to which we will assign appropriate classes, to format our calculator with JavaScript, as shown in the example above.


 

We also note that, at the onclick event for the keys, we entered n (this.id), in this way we automatically retrieve the id that is declared in each input. While the onclick event of button we assign the function operation () that we will create in JavaScript.

We then create the style sheet.


.content {
            margin-left: 2px;
        }
.key{
            background-color: #a5cff3 ;
            color: #175c97;
            font-size: 22pt;
            border: none;
            margin: 4px 2px;
            height: 40px;
	    width: 46px;
        }
.display {
            background: none;
            color: #175c97;
            font-size: 24pt;
            border: #175c97 solid 2px;
            margin: 4px 2px;
            width: 204px;
            height: 40px;            
        }
.egual{
            width: 208px;
        }

Of course, you can customize your calculator with JavaScript with the desired formatting.

Finally we implement the JavaScript code.

The code is really very simple. We create the function n (data) which from time to time takes the data entered by clicking on the keys as it uses the getElementById () method.

Then we create the function that performs the operations using the eval statement which will return the result of our operation.

Finally we realize the function that simply clears the display.


function n(ops){ 
   document.getElementById("operations").value += ops;
}

function op() { 
   document.getElementById("operations").value = eval(document.getElementById("operations").value); 
}

function reset_all() { 
   document.getElementById("operations").value = ""; 
}

As I told you this is a simple method to create a calculator with JavaScript, you can find many other solutions.

Alcuni link utili

Tutorial JavaScript

Decimal to Binary conversion

Decimal to Binary conversion

In this lesson we will learn how to make a decimal to binary conversion in JavaScript.

Try the converter below, write the number and then the conversion will automatically appear in the various systems.

Binary:

Octal:

Hexadecimal:

Furthermore, we will convert the decimal number into binary, octal and hexadecimal.

Decimal to Binary conversion online

Let’s proceed with the implementation of the various functions necessary to carry out the conversion.

First of all we develop the dec_bin function which deals with converting from decimal to binary, considering the remainder of division by 2. The function returns the binary number thus converted.

Then we develop the dec_ott function which deals with converting from decimal to octal, considering the remainder of division by 8. The function returns the octal number thus converted.

Then we implement the dec_esa function which takes care of converting from decimal to hexadecimal, considering the remainder of division by 16. If the remainder is greater than 9, the corresponding letter is taken from the array. The function then returns the converted hexadecimal number.

Finally we insert the change function which activates the automatic change when we insert the value in the decimal field.

So here is the complete JavaScript code for the binary decimal converter:



function dec_bin(num){
	binary = "";

	while(num!=0) {
		r = num % 2; 
		num = (num-r)/2; 
		binary = r + binary;
	}
	
	return binary;
}


function dec_ott(num){ 
	octal = "";

	while(num!=0) {
		r = num % 8; 
		num = (num - r)/8;
		octal = r + octal;
	}
	
	return octal;
}

function dec_esa(num){
	exa = ""; 
	while(num != 0) { 
		r = num % 16; 
		num = (num - r)/16; 
		ar = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
		if (r > 9) 
			r = ar[r]; 
		exa = r + exa ;
	}
	
	return exa ;
}


function change(name) {
		n = document.getElementById("decimale").value;
                result = dec_bin(n);
		result2 = dec_ott(n);
		result3 = dec_esa(n);
		risultato.value=result;
		risultato2.value=result2;
		risultato3.value=result3;
}

In the field, where I insert the decimal number as input, I add the onkeyup event. This causes the other fields to update automatically by calling the change function developed in JavaScript.


 

Clearly this is just a simple way to implement a binary decimal converter, which also allows you to convert to octal and hexadecimal. Feel free to propose your solution in the comments below.

Alcuni link utili

Indice argomenti tutorial JavaScript

Template responsive con html

Come creare un css responsive

Come trovare immagini per il sito web

Quali colori scegliere per un sito web

Quali font scegliere per un sito web

PDF da un form con JavaScript

Binary to decimal conversion

Binary to decimal conversion

In this lesson we will learn how to make a binary to decimal conversion in JavaScript.

Try the converter below, write the number and then the conversion will automatically appear in the various systems.

Decimale:

Binary to decimal conversion in JavaScript

First of all, let’s set up the HTML part of the code.

In our case it will simply be two input boxes:


 

I have inserted on the input box two events:

  • onkeyup which uses for the change function;
  • onkeypress which it uses to check if the number is valid.

Of course I could also handle these events in a different way on the JavaScript side.

We then develop the isValidNumber function, which verifies that the input number is 0 or 1. In this way, if we try to type other numbers or letters they will not be taken into consideration.


        function isValidNumber(e) {

            if (e.keyCode == 48 || e.keyCode == 49) {
                return true;
            }

            return false;
        }

Let’s now develop a function that allows you to transform the binary number under consideration into a decimal.

We follow this method:

  • We transform the number entered in the input field with binary id into a list;
  • Let’s invert the list;
  • We apply the forEach method to scroll through the list.
    • Dunquem, for each element we check that the number is 1. If the condition is satisfied, the reference power is added to the decimal variable, obtained thanks to the use of index.
  • The decimal number obtained is returned.

Here is therefore a possible implementation of the algorithm for binary decimal conversion in JavaScript:


        function bin_dec(num){
           decimal = 0;

            num = Array.from(String(num), Number);
            num = num.reverse();

            num.forEach((number, index) => {

                    if (number == 1) {
                        decimal += Math.pow(2, index);
                    }

                })  

            return decimal;
        }

Now let’s create the change function which calls the conversion function.



        function change(name) {
                b = document.getElementById("binary").value;
                conversion = bin_dec(b);
          
                result.value = conversion;
        }

Clearly this is one of the methods for the binary to decimal system in JavaScript, write your method in the comments below.

Some useful links

Indice argomenti tutorial JavaScript

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

15 puzzle game

Inlcudes() String Method

JavaScript array includes()

Math.random

parseInt JavaScript

JavaScript to do list

JavaScript to do list

In this lesson we will create a simple JavaScript to do list, a classic JavaScript exercise that allows you to experiment with the methods learned so far.

To carry out this project, in fact, we will use some methods to manipulate the DOM in JavaScript.

In the meantime, try the project that we are going to create together by inserting an item and then clicking on the add button in the figure below:

App To Do List

To do list in JavaScript – development

First we create the HTML code of the project.

So let’s create an input box with a button and prepare a list where all the elements that we will add gradually will appear.





We then create any CSS to give a graphic touch, for example I have created this:



.container{
    background: #ff6676;
    padding: 30px;   
    display: flex;
    flex-direction: column;
}

.container h3{
    color: white;
    text-align: center;
    margin-bottom: 15px;
    height: auto;
}

form{
    display: flex;
    width: 100%;
}

.textInput{
    width: 100%;
    border: none;
    padding: 14px;
}

#add{
    width: 30%;
    cursor: pointer;
    background: #2c45a3;
    border: none;
    color: white;
    font-size: 18px;
}

ul#lists{
    display: flex;
    flex-direction: column;
    margin: 10px 0;
    list-style: none;
}

ul#lists li{
    padding: 12px;
    background: white;
    border: 1px solid #2c45a3;
    display:flex;
    justify-content: space-between;
}

.delete{
    padding: 10px;
    cursor: pointer;
    border: none;
    background: #ff6676;
    color: white;
}

Finally we develop the JavaScript code necessary to make our to do list work:



const buttonAdd = document.getElementById('add');
const lists = document.getElementById('lists');
const textInput = document.querySelector('.textInput');

buttonAdd.addEventListener('click', generateList);

function generateList(event) {
    event.preventDefault();

    if (textInput.value === '') return;

    const li =  document.createElement('li');
    lists.appendChild(li);    
    li.appendChild(document.createTextNode(textInput.value));
    
    const buttonDelete = document.createElement('button');
    buttonDelete.className = 'delete';
    buttonDelete.appendChild(document.createTextNode('X'));    
    li.appendChild(buttonDelete);
    
    textInput.value = '';
    
    buttonDelete.addEventListener('click', (event) =>{
        const parentNodeEl = event.target.parentNode;
        setTimeout(() =>{
            parentNodeEl.remove();
        }, 500)
        
    });
         
}



First of all we checked that the input box contained some text and otherwise we exit the function with a return. In this way, if the box is empty, a list is not created.

After, we used the addEventListener method to capture the first click on the add button to add an item in the list and then on the delete button to delete the corresponding item.

Within the generateList function we used the createElement and createTextNode methods respectively to create the necessary tags (li and button) and add text.

After adding the entry we empty the input box.

Conclusion

In this lesson we have developed a simple to do list in JavaScript, try developing one yourself and write in the comments below. In the next lessons we will develop many other creative projects.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

JavaScript eval

JavaScript eval

The eval function in JavaScript evaluates the expression passed as an argument and executes it if there is an operation.

The syntax is as follows: eval(string).

JavaScript eval examples

Here is a series of demonstrative examples on the use of eval.



console.log(eval('2 + 13'));
var x = 10;
var y = 3;
console.log(eval('x + y'));
console.log(eval(' x / y'));

However, remember that this function is slower than the alternatives.

It can also be dangerous as it runs the code with page administrator privileges.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript functions and return

JavaScript Callback

Callbacks

Array method and callback function

Callback functions – examples