w3resource

JavaScript: Get the first element of an array

JavaScript Array: Exercise-1 with Solution

Check Array Input

Write a JavaScript function to check whether an 'input' is an array or not.

Test Data:
console.log(is_array('w3resource'));
console.log(is_array([1, 2, 4, 0]));
false
true

Sample Solution:

JavaScript Code:

// Function to check if the input is an array
var is_array = function(input) {
  // Using toString method to get the class of the input and checking if it is "[object Array]"
  if (toString.call(input) === "[object Array]")
    // Return true if the input is an array
    return true;
  // Return false if the input is not an array
  return false;   
};

// Testing the function with a string
console.log(is_array('w3resource'));

// Testing the function with an array
console.log(is_array([1, 2, 4, 0]));

Output:

false
true

Flowchart:

Flowchart: JavaScript: Display the colors entered in an array by a specific format

ES6 Version:

// Function to check if the input is an array
const is_array = input => {
  // Using toString method to get the class of the input and checking if it is "[object Array]"
  if (toString.call(input) === "[object Array]") {
    // Return true if the input is an array
    return true;
  }
  // Return false if the input is not an array
  return false;
};

// Testing the function with a string
console.log(is_array('w3resource'));

// Testing the function with an array
console.log(is_array([1, 2, 4, 0]));

Live Demo:

See the Pen JavaScript - Get the first element of an array- array-ex-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that checks if a given variable is an array using Array.isArray and also confirms its length property exists.
  • Write a JavaScript function that determines if an input is an array by examining its constructor and Object.prototype.toString output.
  • Write a JavaScript function that distinguishes between arrays and array-like objects by testing for the push method.
  • Write a JavaScript function that checks whether an input is a true array and returns a custom error message if not.

Go to:


PREV : Javascript Array Exercises
NEXT : Clone Array.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.