Program JavaScript untuk Mengonversi Tanggal ke Angka

Contoh: Konversi Tanggal ke Angka // program to convert date to number // create date const d1 = new Date(); console.log(d1); // converting to number const result = d1.getTime(); console.log(result); Keluaran Mon Nov 09 2020 10:52:32 GMT+0545 (Nepal Time) 1604898452084 Dalam contoh di atas, new Date() konstruktor digunakan untuk membuat objek tanggal. Itu new Date() […]

Read more »

Program JavaScript untuk Menulis ke Konsol

Contoh: Menggunakan console.log() // program to write to console // passing number console.log(8); // passing string console.log(‘hello’); // passing variable const x = ‘hello’; console.log(x); // passing function function sayName() { return ‘Hello John’; } console.log(sayName()); // passing string and a variable const name=”John”; console.log(‘Hello ‘ + name); // passing object let obj = { […]

Read more »

Program JavaScript untuk Menghapus Semua Spasi Putih Dari Teks

Contoh 1: Menggunakan split() dan join() // program to trim a string const string = ‘ Hello World ‘; const result = string.split(‘ ‘).join(”); console.log(result); Keluaran HelloWorld Pada program di atas, Itu split(‘ ‘) metode ini digunakan untuk membagi string menjadi elemen array individu. [“”, “”, “”, “”, “”, “”, “Hello”, “World”, “”, “”, “”, […]

Read more »

Program JavaScript untuk Mendapatkan Dimensi Gambar an

Contoh: Dapatkan Dimensi Gambar // program to get the dimensions of an image const img = new Image(); // get the image img.src=”https://cdn.programiz.com/sites/tutorial2program/files/cover-artwork.png”; // get height and width img.onload = function() { console.log(‘width ‘ + this.width) console.log(‘height ‘+ this.height); } Keluaran width 1040 height 922 Pada program di atas, new Image() konstruktor digunakan untuk membuat […]

Read more »

Program JavaScript untuk Melewati Fungsi sebagai Parameter

Contoh: Fungsi sebagai Parameter // program to pass a function as a parameter function greet() { return ‘Hello’; } // passing function greet() as a parameter function name(user, func) { // accessing passed function const message = func(); console.log(`${message} ${user}`); } name(‘John’, greet); name(‘Jack’, greet); name(‘Sara’, greet); Keluaran Hello John Hello Jack Hello Sara Dalam […]

Read more »

Program JavaScript untuk Memeriksa apakah suatu Angka Float atau Integer

Contoh 1: Menggunakan Number.isInteger() // program to check if a number is a float or integer value function checkNumber(x) { // check if the passed value is a number if(typeof x == ‘number’ && !isNaN(x)){ // check if it is integer if (Number.isInteger(x)) { console.log(`${x} is integer.`); } else { console.log(`${x} is a float value.`); […]

Read more »

Program JavaScript untuk Menerapkan Antrian

Antrian adalah struktur data yang mengikuti Masuk Pertama Keluar Pertama (FIFO) prinsip. Elemen yang ditambahkan pertama diakses terlebih dahulu. Ini seperti berada dalam antrian untuk mendapatkan tiket bioskop. Yang pertama mendapatkan tiket terlebih dahulu. Contoh: Implementasikan Antrian // program to implement queue data structure class Queue { constructor() { this.items = []; } // add […]

Read more »

Program JavaScript untuk Menerapkan Stack

Tumpukan adalah struktur data yang mengikuti Terakhir Masuk Pertama Keluar (LIFO) prinsip. Elemen yang ditambahkan terakhir diakses terlebih dahulu. Ini seperti menumpuk buku Anda di atas satu sama lain. Buku yang Anda taruh akhirnya datang lebih dulu. Contoh: Implementasikan Tumpukan // program to implement stack data structure class Stack { constructor() { this.items = []; […]

Read more »

Program JavaScript untuk Melakukan Fungsi Overloading

Dalam pemrograman, fungsi overloading mengacu pada konsep di mana beberapa fungsi dengan nama yang sama dapat memiliki implementasi yang berbeda. Namun, dalam JavaScript, jika ada beberapa fungsi dengan nama yang sama, fungsi yang ditentukan terakhir akan dieksekusi. Fitur fungsi overloading dapat diimplementasikan dalam beberapa cara lain. Contoh 1: Menggunakan Pernyataan if/else-if // program to perform […]

Read more »

Program JavaScript untuk Menghasilkan Rentang Angka dan Karakter

Contoh: Hasilkan Rentang Karakter // program to generate range of numbers and characters function* iterate(a, b) { for (let i = a; i <= b; i += 1) { yield i } } function range(a, b) { if(typeof a === ‘string’) { let result = […iterate(a.charCodeAt(), b.charCodeAt())].map(n => String.fromCharCode(n)); console.log(result); } else { let result […]

Read more »

Program JavaScript untuk Melewati Parameter ke Fungsi setTimeout()

Itu setTimeout() metode mengeksekusi blok kode setelah waktu yang ditentukan. Metode mengeksekusi kode hanya sekali. Sintaks JavaScript setTimeout yang umum digunakan adalah: setTimeout(function, milliseconds); Parameternya adalah: fungsi – fungsi yang berisi blok kode milidetik – waktu setelah fungsi dijalankan Contoh 1: Melewati Parameter ke setTimeout // program to pass parameter to a setTimeout() function function […]

Read more »

Program JavaScript Untuk Bekerja Dengan Konstanta

Contoh: Bekerja Dengan Konstanta // program to include constants const a = 5; console.log(a); // constants are block-scoped { const a = 50; console.log(a); } console.log(a); const arr = [‘work’, ‘exercise’, ‘eat’]; console.log(arr); // add elements to arr array arr[3] = ‘hello’; console.log(arr); // the following code gives error // changing the value of a […]

Read more »

Program JavaScript untuk Memeriksa Apakah Variabel adalah Tipe Fungsi

Contoh 1: Menggunakan instanceof Operator // program to check if a variable is of function type function testVariable(variable) { if(variable instanceof Function) { console.log(‘The variable is of function type’); } else { console.log(‘The variable is not of function type’); } } const count = true; const x = function() { console.log(‘hello’) }; testVariable(count); testVariable(x); Keluaran […]

Read more »

Program JavaScript untuk Memvalidasi Alamat Email

Contoh: Menggunakan Regex // program to validate an email address function validateEmail(email_id) { const regex_pattern = /^(([^<>()[]\.,;:s@”]+(.[^<>()[]\.,;:s@”]+)*)|(“.+”))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/; if (regex_pattern.test(email_id)) { console.log(‘The email address is valid’); } else { console.log(‘The email address is not valid’); } } validateEmail(‘abc123@gmail.com’); validateEmail(‘hello@com’); Keluaran The email address is valid The email address is not valid Dalam program di atas, pola […]

Read more »

Program JavaScript Untuk Mendapatkan URL Saat Ini

Contoh: Dapatkan URL Saat Ini // program to get the URL const url1 = window.location.href; const url2 = document.URL; console.log(url1); console.log(url2); Keluaran https://www.google.com/ https://www.google.com/ Pada program di atas, window.location.href properti dan document.URL properti digunakan untuk mendapatkan URL halaman saat ini. Keduanya window.location.href dan document.URL properties mengembalikan URL halaman saat ini.

Read more »

Program Javascript untuk Menghasilkan Angka Acak Antara Dua Angka

Jika Anda ingin menemukan bilangan bulat acak di antaranya min (termasuk) untuk maksimal (inklusif), Anda dapat menggunakan rumus berikut: Math.floor(Math.random() * (max – min + 1)) + min Contoh: Nilai Bilangan Bulat Antara Dua Angka // input from the user const min = parseInt(prompt(“Enter a min value: “)); const max = parseInt(prompt(“Enter a max value: […]

Read more »

Program JavaScript untuk Menetapkan Nilai Parameter Default Untuk Suatu Fungsi

Sintaks untuk menetapkan nilai parameter default untuk suatu fungsi adalah: function functionName(param1=default1, param2=default2, …) { // function body } Contoh 1: Tetapkan Nilai Parameter Default Untuk Fungsi // program to set default parameter value function sum(x = 3, y = 5) { // return sum return x + y; } console.log(sum(5, 15)); console.log(sum(7)); console.log(sum()); Keluaran […]

Read more »

Program JavaScript untuk Menetapkan Nilai Parameter Default Untuk Suatu Fungsi

Sintaks untuk menetapkan nilai parameter default untuk suatu fungsi adalah: function functionName(param1=default1, param2=default2, …) { // function body } Contoh 1: Tetapkan Nilai Parameter Default Untuk Fungsi // program to set default parameter value function sum(x = 3, y = 5) { // return sum return x + y; } console.log(sum(5, 15)); console.log(sum(7)); console.log(sum()); Keluaran […]

Read more »

Program JavaScript Untuk Memeriksa Apakah Variabel Tidak Terdefinisi atau null

Contoh 1: Centang undefined atau null // program to check if a variable is undefined or null function checkVariable(variable) { if(variable == null) { console.log(‘The variable is undefined or null’); } else { console.log(‘The variable is neither undefined nor null’); } } let newVariable; checkVariable(5); checkVariable(‘hello’); checkVariable(null); checkVariable(newVariable); Keluaran The variable is neither undefined nor […]

Read more »

Program JavaScript untuk Mendapatkan Ekstensi File

Contoh 1: Menggunakan split() dan pop() // program to get the file extension function getFileExtension(filename){ // get file extension const extension = filename.split(‘.’).pop(); return extension; } // passing the filename const result1 = getFileExtension(‘module.js’); console.log(result1); const result2 = getFileExtension(‘module.txt’); console.log(result2); Keluaran js txt Dalam program di atas, ekstensi nama file diekstraksi menggunakan split() metode dan […]

Read more »

Program JavaScript untuk Menyertakan file JS dalam file JS lain

Contoh: Menggunakan impor/ekspor Mari kita buat file bernama modul.js (nama file bisa apa saja) dengan konten berikut: // program to include JS file into another JS file const message=”hello world”; const number = 10; function multiplyNumbers(a, b) { return a * b; } // exporting variables and function export { message, number, multiplyNumbers }; Untuk […]

Read more »

Program JavaScript untuk Membagi Array menjadi Potongan yang Lebih Kecil

Contoh 1: Split Array Menggunakan slice() // program to split array into smaller chunks function splitIntoChunk(arr, chunk) { for (i=0; i < arr.length; i += chunk) { let tempArray; tempArray = arr.slice(i, i + chunk); console.log(tempArray); } } const array = [1, 2, 3, 4, 5, 6, 7, 8]; const chunk = 2; splitIntoChunk(array, chunk); […]

Read more »

Program JavaScript Untuk Melakukan Persimpangan Antara Dua Array

Contoh 1: Lakukan Persimpangan Menggunakan Set // program to perform intersection between two arrays using Set // intersection contains the elements of array1 that are also in array2 function performIntersection(arr1, arr2) { // converting into Set const setA = new Set(arr1); const setB = new Set(arr2); let intersectionResult = []; for (let i of setB) […]

Read more »