Simple Logic in javascript

Write a function setFirstElement that takes an array and an arbitrary variable. The variable should be inserted as the first element in the array. The array should be returned.
setFirstElement([1, 2], 3) should return [3, 2].
setFirstElement([], 1) should returns [1].
setFirstElement(["a", "b", "c"], "x") should return [“x”,“b”,“c”].

Have you worked out your algorithm yet? What code have you tried to write?

Yes, I tried below code.

var setFirstElement = function([a, b],c) {
 if(a >= 1 && b >= 1){
   setFirstElement = [c,b];
   return setFirstElement[0] = c;
 } else {
     setFirstElement[0]= c;
      return setFirstElement = [c];

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


Can you explain why you created the first if statement? Why are you checking that both a and b are greater or equal to 1?

  if (a >= 1 && b >= 1) {
    setFirstElement = [c, b];
    return setFirstElement[0] = c;


Also, you declared setFirstElement to be a function and then inside the function you attempt to assign it an array?

In question itself it is written that when empty array is given it should return [1].
As per the question i assigned an array in function.

please find the below code.

function setFirstElement(arr, arbVar) {

arr = [];
arr[0] = arbVar;
return (arr);


var result = setFirstElement([1, 2],3);
var result1 = setFirstElement([],1);
var result2 = setFirstElement([‘a’,‘b’,‘c’],‘x’);


Are you trying to solve this algorithm? I’ll give you a hint if you haven’t solved it. Look at the array methods shift() and unshift().

Hopefully my hint wasn’t too revealing.

var setFirstElement = function (array,x){
array[0]= x;
return array;

The below works:)

var setFirstElement = function(arr, varArt) {
var arrList = arr;
arrList[0] = varArt;
return arrList;
1 Like