You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).


Given ::
Output ::

JavaScript Code

function rotate(matrix) {
    var n = matrix.length;
    for (var i = 0; i < n / 2; i++) {
        for (var j = 0; j < Math.ceil(n/2); j++) {
            var temp = matrix[i][j];
            matrix[i][j] = matrix[n-1-j][i];
            matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
            matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
            matrix[j][n-1-i] = temp;
    return matrix;


  1. You should be using Math.floor, not Math.ceil. Test your code out on a 3x3 Matrix.

  2. And there is a period in your arrays

  3. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here.
    Kindly keep blogging. If anyone wants to become a Front end developer learn from HTML5 CSS3 Javascript Online Training from India .
    or learn thru HTML5 CSS3 Javascript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry.
    HTML5 CSS3 Javascript Online Training from India



Popular Posts